Gson调用在多个类上返回空对象

时间:2014-12-23 20:06:34

标签: java json gson

我试图序列化以序列化我在下面包含的json字符串。

 {
        "mood": {
            "is_featured": true,
            "description": null,
            "title": "2014 ",
            "ordering": null,
            "is_recently_modified": true,
            "is_test": false,
            "tracks": [

            {
                "album": {
                    "release_date": "2014-11-06",
                    "id": 359778,
                    "name": "Amansız Gücenik"
                },
                "name": "Hırpalandı Mayıs",
                "artist": {
                    "id": 491169,
                    "name": "Ceylan Ertem"
                },
                "duration": 227,
                "isrc": "TRA161400207",
                "id": 3903997
            },
            {
                "album": {
                    "release_date": "2013-08-05",
                    "id": 329129,
                    "name": "For Fuld Musik - 25 Danske Sommer Pop & Rock Hits Vol. 2"
                },
                "name": "Am I Wrong",
                "artist": {
                    "id": 755957,
                    "name": "Nico & Vinz"
                },
                "duration": 387,
                "isrc": "NO2G31301011",
                "id": 3655085
            }
        ],
        "image_url": "some_url",
        "is_recently_created": true,
        "id": 128
    }
}

我正在使用此gson调用来序列化它

Mood mood = new Gson().fromJson(result, Mood.class);

我的班级结构就像这样。

public class Mood {

    private boolean is_featured;
    private boolean is_recently_modified;
    private boolean is_recently_created;
    private boolean is_test;


    private String  description;
    private String  title;
    private String  image_url;

    private int     id;
    private int     ordering;

    private Track[] tracks;



    public static class MoodContainer {
        public Mood[] moods;
    }


}


public class Track {

    //variables
    private Album       album;
    private Artist      artist;
    private Provider    provider;


    private String      secure_url;
    private String      name;
    private String      region;
    private String      isrc;

    private int         duration;
    private int         track_order;
    private int         id;

}

对于任何其他类变量,它都是这样的。当我尝试使用上面的调用时,我最终得到了具有所有空值的对象。有一点需要注意的是,json字符串中没有提供某些字段,因为不同的api调用提供了这些json字符串的不同部分。我做错了什么?

2 个答案:

答案 0 :(得分:3)

您提供的根JSON对象具有属性mood - 因此您要么有两个反序列化选项才能正常工作:

  1. Mood类包含在另一个对象中:

    public class MoodWrapper { private Mood mood; }

    并将反序列化代码更改为

    MoodWrapper moodWrapper = new Gson().fromJson(result, MoodWrapper.class);

  2. 反序列化时跳过根对象:

    final Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonObject rootObj = parser.parse(json).getAsJsonObject();
    Mood mood = gson.fromJson(rootObj.getAsJsonObject("mood"), Mood.class);
    

答案 1 :(得分:1)

JSON字符串中的顶级元素应该是对象的属性,而不是外部元素"心情"你有。