大家好我用gson反序列化我的json有些麻烦,当我尝试反序列化到我的列表中时我没有发现任何错误但是每当我尝试显示List的内容时我得到了一个java.lang.NullPointerException。 / p>
这是json:
{
"_id": "577f81286ed8b475f5faf6fb",
"title": "bad (feat. vassy) [radio edit]",
"album": "Listen",
"artist": {
"_id": "577f81140e8784358e32ae2d",
"name": "david guetta"
},
"genre": {
"_id": "577f81140e8784358e32ae2e",
"name": "dance"
},
"duration": "2m50s",
"year": 2014,
"artwork": {
"small": "https://i.scdn.co/image/f59354f8d3f2841e44c1bd7aa0cd55a22843cfc7",
"medium": "https://i.scdn.co/image/9b092f765831793404d46b816d688135ff32735f",
"large": "https://i.scdn.co/image/6e94ab39c917096d876b895dbab0019953d27a96",
"default": "https://i.scdn.co/image/6e94ab39c917096d876b895dbab0019953d27a96"
},
"extraGenres": [],
"extraArtists": []
}

这是我的模特:
public class SongDetails {
public String _id;
public String title;
public String album;
public String duration;
public int year;
@SerializedName("artist") Artist artist;
public static class Artist {
public String _id;
public String name;
}
@SerializedName("genre") Genre genre;
public static class Genre {
public String _id;
public String name;
}
@SerializedName("artwork") Artwork artwork;
public static class Artwork {
public String small;
public String medium;
public String large;
@SerializedName("default")
public String defaultX;
}
@SerializedName("votes") public VotesPlayer votes;
public static class VotesPlayer {
public int upVotes;
public int downVotes;
public int standing;
public String by;
}
}

我尝试像这样反序列化:
Gson gson = new Gson();
Log.d("playdetails to des", toDeserialize);
// toDeserialize = {"_id":"577f81286ed8b475f5faf6fb","title":"bad (feat. vassy) [radio edit]","album":"Listen","artist":{"_id":"577f81140e8784358e32ae2d","name":"david guetta"},"genre":{"_id":"577f81140e8784358e32ae2e","name":"dance"},"duration":"2m50s","year":2014,"artwork":{"small":"https://i.scdn.co/image/f59354f8d3f2841e44c1bd7aa0cd55a22843cfc7","medium":"https://i.scdn.co/image/9b092f765831793404d46b816d688135ff32735f","large":"https://i.scdn.co/image/6e94ab39c917096d876b895dbab0019953d27a96","default":"https://i.scdn.co/image/6e94ab39c917096d876b895dbab0019953d27a96"},"extraGenres":[],"extraArtists":[]}
try {
Response r = gson.fromJson(toDeserialize, Response.class);
Log.d("deser details", r.myPlaylistDetails.size()+"");
} catch (Exception e) {
e.printStackTrace();
}
public class Response {
public List<SongDetails> myPlaylistDetails;
}
&#13;
我收到了这个错误
W / System.err:java.lang.NullPointerException:尝试调用接口方法&#39; int java.util.List.size()&#39;在空对象引用上
位于:&#34; Log.d(&#34; deser details&#34;,r.myPlaylistDetails.size()+&#34;&#34;);&#34; < / p>
答案 0 :(得分:0)
我已经取代了
Response r = gson.fromJson(toDeserialize, Response.class);
通过正确反序列化我的json
SongDetails r = gson.fromJson(toDeserialize, SongDetails.class);
然后显示我的详细信息:
Log.d("deser details", r.title);