gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:14:07 25 4
gpt4 key购买 nike

我正在尝试序列化以序列化我在下面包含的 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 字符串的不同部分。我做错了什么?

最佳答案

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

  1. 将您的 Mood 类包装在另一个对象中,如下所示:

    public class MoodWrapper { private 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);

关于java - Gson 调用在多个类上返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27627277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com