【问题标题】:Deserializing inner class with gson returns null使用 gson 反序列化内部类返回 null
【发布时间】:2013-07-16 12:41:26
【问题描述】:

我想使用 Gson 将我的 JSON 反序列化为对象。 我已经定义了适当的类,其中一些类的对象包含在其他对象中。 在尝试反序列化整个 JSON 时,我得到了 null 值,因此我开始将其拆分。

我达到了所有低级类都支持他们自己的地步,但是当尝试反序列化为一个包含该较小对象实例的对象时 - 每件事都返回为 null。

我的部分 JSON:

{
  "user_profile": {
    "pk": 1,
    "model": "vcb.userprofile",
    "fields": {
      "photo": "images/users/Screen_Shot_2013-03-18_at_5.24.13_PM.png",
      "facebook_url": "https://google.com/facebook",
      "site_name": "simple food",
      "user": {
        "pk": 1,
        "model": "auth.user",
        "fields": {
          "first_name": "blue",
          "last_name": "bla"
        }
      },
      "site_url": "https://google.com/"
    }
  }
}

UserProfile 类:

public class UserProfile {
    private int pk;
    private String model;
    private UPfields fields = new UPfields();//i tried with and without the "new"
}

UPfields 类:

public class UPfields {
    private String photo;
    private String facebook_url;
    private String site_name;
    private User user;
    private String site_url;
}

用户类别:

public class User {
    private int pk;
    private String model;
    private Ufields fields;
}

Ufields 类:

public class Ufields {
    private String first_name;
    private String last_name;
}

在我的主要调用中:

Gson gson = new Gson();
UserProfile temp = gson.fromJson(json, UserProfile.class);

所以我的临时对象只包含空值。 我尝试将类更改为静态,但它不起作用。 UPfields 对象和所有较低的对象都可以正常工作。

有什么建议吗?

当我删除

"{
  "user_profile":"

它是右括号,反序列化为 user_profile 对象有效。

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    为了解析这个json 示例,您必须创建辅助类,其中将包含名为user_profile 的字段,类型为UserProfile

    public class UserProfileWrapper {
        private UserProfile user_profile;
    }
    

    并用这个类解析这个json字符串:

    UserProfileWrapper temp = gson.fromJson(json, UserProfileWrapper.class);
    

    【讨论】:

    • 我不同意。他最好从 JSON 对象中解析出user_profile 字段的值,而不是引入一个多余的包装类。
    • @TomG 好吧,你能提供简单的方法吗,如何使用 Gson 做到这一点?
    • @user2585252 在我看来,你做错了什么。因为我也在你的课程和你的 gson 示例中尝试过它,它就像一个魅力。
    • Gr8,包装器工作了!...那我为什么需要它,我是否总是必须使用包装器?因为 UPfields、User 和 Ufields 类不需要一个。
    • @user2585252 好吧,实际上,您的班级 UserProfile 的规范 json 字符串看起来像:{"pk":1,"model":"vcb.userprofile","fields":{"photo":"images/users/Screen_Shot_2013-03-18_at_5.24.13_PM.png","facebook_url":"https://google.com/facebook","site_name":"simple food","user":{"pk":1,"model":"auth.user","fields":{"first_name":"blue","last_name":"bla"}},"site_url":"https://google.com/"}}
    【解决方案2】:

    Gson 首先解析最外面的对象,在您的例子中,它有一个字段 user_profile。您的 UserProfile 类没有 user_profile 字段,因此它无法将其反序列化为该类的实例。您应该尝试反序列化 user_profile 字段的

    【讨论】:

    • 嗯,你能提供简单的方法吗,如何使用Gson做到这一点?
    • 哦,请告诉我如何...我看到当我删除 { "user_profile":....} 时它可以工作...那么问题是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2016-01-30
    • 2021-12-08
    相关资源
    最近更新 更多