【问题标题】:Gson toJson(), weird behavior (produce empty json)Gson toJson(),奇怪的行为(产生空的 json)
【发布时间】:2016-10-18 02:47:49
【问题描述】:

我在使用 Gson 序列化/反序列化此类时遇到问题:

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.fromJson("{\"id\":\"1465988493\"}");
Log.i(TAG, "Test: " + test.toJson());
Log.i(TAG, "Test id: " + test.getId());

它按预期工作并打印:

测试:{"id":"1465988493"}

测试编号:1465988493

所以在调用 toJson 之后调用 getter 会使 toJson() 工作。什么鬼???

最后一件事,如果我将 id 初始化为 null:

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());

打印:

测试:{"id":"1465988493"}

所以,我有解决方案(将我的所有字段初始化为空),但我想了解有什么问题??

【问题讨论】:

  • 我无法重现这个。不要对 JSON 字符串使用单引号(尽管 Gson 能够解析它们)。
  • 你有没有使用过 proguard 的机会?没有Log.i(TAG, "Test id: " + test.getId()); 整个“id 东西”可以在优化中删除,因为你没有使用它
  • 谢谢。双引号也有同样的问题(我在代码中使用双引号,我在写帖子时改为单引号,以提高可读性)。是的,我正在使用 Proguard,为什么?
  • 看到您的编辑。好的,非常感谢,确实proguard是原因。请发布一个答案,我会接受它(并从这个帖子的接受答案提供proguard配置:stackoverflow.com/questions/23826171/…)。

标签: java android gson to-json


【解决方案1】:

只是proguard问题。如果您使用 proguard,请记住,如果您不使用 proguard,它可以从类中删除一些字段。例如,您的应用程序不使用类吸气剂。如此简单的方法只需添加注释即可:

@SerializedName("id")
@Keep
private String mId;

或者将保留规则添加到您的 proguard 文件中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    相关资源
    最近更新 更多