【问题标题】:Trying to read JSON (using GSON) into an Object which has another object as a field.尝试将 JSON(使用 GSON)读入一个具有另一个对象作为字段的对象。
【发布时间】:2014-06-25 02:49:19
【问题描述】:

所以我使用 Google 的 GSON 库来理解 JSON 字符串。我让它在我保存的对象是User 的地方工作,声明如下:

User user = gson.fromJson(string, User.class),

但我似乎无法理解如何使用“嵌套对象”保存字符串。这是给我错误的声明:

Gson gson = new Gson();
Request request = gson.fromJson(requestInput, Request.class);

requestInput 在哪里

String requestInput = "{key: \"123\", requestType: \"POST\", requestModelType: \"USER\","
            + " obj: {username: \"alex\", email: \"email@gmail.com\", password:\"pass\"}}";

我的User 类如下所示:

public class User implements Serializable{
    private static final long serialVersionUID = -24243416292823789L;

    private String username;
    private String email;
    private String password;
    private List<Circle> circles;
    private List<Notification> notifications;
    ...

而我的Request 看起来像这样:

public class Request {

    private String key;
    private String requestType;
    private String requestModelType;
    private User user; 
    ...

最后,我收到以下错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
...

非常感谢您对此提供任何帮助或提出更好设计的建议!

【问题讨论】:

    标签: java json rest gson


    【解决方案1】:

    你需要使用:

    @SerializedName("obj") 私人用户用户;

    这样 GSON 就知道 JSON 中的“obj”应该映射到用户字段。

    你显示的实际错误有点不同,我不确定你是如何得到那个特定错误的——这意味着你有一些东西在 Java 中声明为字符串,但在 JSON 中声明为对象。

    【讨论】:

    • 这确实有帮助!想了半天都没有想到要查注解!
    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多