Gson toJson(),奇怪的行为(产生空 json)
Gson toJson(), weird behavior (produce empty json)
我在使用 Gson 序列化/反序列化此 class 时遇到问题:
public class Test {
@SerializedName("id")
private String mId;
public String getId() { return mId; }
public static Test fromJson(String json) { return new Gson().fromJson(json, Test.class); }
public String toJson() { return new Gson().toJson(this, Test.class); }
}
如果我运行这个:
Test test = Test.fromJson("{\"id\":\"1465988493\"}");
Log.i(TAG, "Test: " + test.toJson());
//Log.i(TAG, "Test id: " + test.getId());
它打印:
Test: {}
但是如果我运行这个:
Test test = Test.fromJson("{\"id\":\"1465988493\"}");
Log.i(TAG, "Test: " + test.toJson());
Log.i(TAG, "Test id: " + test.getId());
它按预期工作并打印:
Test: {"id":"1465988493"}
Test id: 1465988493
因此在调用 toJson 之后调用 getter 使 toJson() 起作用。什么鬼???
最后,如果我将 id 初始化为空:
public class Test {
@SerializedName("id")
private String mId = null; // <- Init to null
public String getId() { return mId; }
public static Test fromJson(String json) { return new Gson().fromJson(json, Test.class); }
public String toJson() { return new Gson().toJson(this, Test.class); }
}
然后一切都按预期工作,这段代码:
String testJson = "{\"id\":\"1465988493\"}";
Test test = Test.fromJson(testJson);
Log.i(TAG, "Test: " + test.toJson());
//Log.i(TAG, "Test id: " + test.getId());
打印:
Test: {"id":"1465988493"}
所以,我有解决方案(将我所有的字段初始化为空),但我想了解哪里出了问题??
只是proguard问题。如果您使用 proguard,请记住如果您不使用它,proguard 可以从 class 中删除一些字段。例如,您的应用不使用 class 的 getter。如此简单的方法只需添加注释以使其保持如下状态:
@SerializedName("id")
@Keep
private String mId;
或者将 keep 规则添加到您的 proguard 文件中。
我在使用 Gson 序列化/反序列化此 class 时遇到问题:
public class Test {
@SerializedName("id")
private String mId;
public String getId() { return mId; }
public static Test fromJson(String json) { return new Gson().fromJson(json, Test.class); }
public String toJson() { return new Gson().toJson(this, Test.class); }
}
如果我运行这个:
Test test = Test.fromJson("{\"id\":\"1465988493\"}");
Log.i(TAG, "Test: " + test.toJson());
//Log.i(TAG, "Test id: " + test.getId());
它打印:
Test: {}
但是如果我运行这个:
Test test = Test.fromJson("{\"id\":\"1465988493\"}");
Log.i(TAG, "Test: " + test.toJson());
Log.i(TAG, "Test id: " + test.getId());
它按预期工作并打印:
Test: {"id":"1465988493"}
Test id: 1465988493
因此在调用 toJson 之后调用 getter 使 toJson() 起作用。什么鬼???
最后,如果我将 id 初始化为空:
public class Test {
@SerializedName("id")
private String mId = null; // <- Init to null
public String getId() { return mId; }
public static Test fromJson(String json) { return new Gson().fromJson(json, Test.class); }
public String toJson() { return new Gson().toJson(this, Test.class); }
}
然后一切都按预期工作,这段代码:
String testJson = "{\"id\":\"1465988493\"}";
Test test = Test.fromJson(testJson);
Log.i(TAG, "Test: " + test.toJson());
//Log.i(TAG, "Test id: " + test.getId());
打印:
Test: {"id":"1465988493"}
所以,我有解决方案(将我所有的字段初始化为空),但我想了解哪里出了问题??
只是proguard问题。如果您使用 proguard,请记住如果您不使用它,proguard 可以从 class 中删除一些字段。例如,您的应用不使用 class 的 getter。如此简单的方法只需添加注释以使其保持如下状态:
@SerializedName("id")
@Keep
private String mId;
或者将 keep 规则添加到您的 proguard 文件中。