如何通过Gson将json数组包装到包含此数组的集合的自定义对象中?我有以下json字符串:
[
{
"showId":410,
"siteId":85,
"name":"Майстер і маргарита",
"duration":7200,
"providerId":1016,
"events":[
{
"siteId":85,
"eventSiteId":0,
"providerId":1016,
"eventId":1178,
"hallId":0,
"premiere":false,
"origin":"20140912190000"
}
]
}
]
并希望将其反序列化为下面的对象:
public class Shows {
private List<Show> shows;
public List<Show> getShows() {
return shows;
}
public void setShows(List<Show> shows) {
this.shows = shows;
}
}
答案 0 :(得分:0)
你可以试试这个。
//lets assume the json string to be in the variable data
Shows shows = new Gson().fromJson(data, Shows.class);
答案 1 :(得分:0)
此Json
消息代表List<Show>
,Show
也包含List
个事件。
这不是Json
的{{1}},如果是的话,它应该是这样的。
Shows
但您可以尝试这种方式获取{
"shows":[
{
"showId":410,
"siteId":85,
"name":"Майстер і маргарита",
"duration":7200,
"providerId":1016,
"events":[
{
"siteId":85,
"eventSiteId":0,
"providerId":1016,
"eventId":1178,
"hallId":0,
"premiere":false,
"origin":"20140912190000"
}
]
}
]
}
并将其设置为List<Show>
你可以这样试试。
Shows
我的结果。
显示{shows = [显示{showId = 410,siteId = 85,name ='Майстерімаргарита', duration = 7200,providerId = 1016,events = [Events {siteId = 85, eventSiteId = 0,providerId = 1016,eventId = 1178,hallId = 0, premiere = false,origin ='20140912190000'}]}]}
我的Type collectionType = new TypeToken<List<Show>>() {
}.getType();
String jsonString="[\n" +
"\n" +
" {\n" +
" \"showId\":410,\n" +
" \"siteId\":85,\n" +
" \"name\":\"Майстер і маргарита\",\n" +
" \"duration\":7200,\n" +
" \"providerId\":1016,\n" +
" \"events\":[\n" +
" {\n" +
" \"siteId\":85,\n" +
" \"eventSiteId\":0,\n" +
" \"providerId\":1016,\n" +
" \"eventId\":1178,\n" +
" \"hallId\":0,\n" +
" \"premiere\":false,\n" +
" \"origin\":\"20140912190000\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"\n" +
"]";
List<Show> showList=new Gson().fromJson(jsonString,collectionType);
Shows shows=new Shows();
shows.setShows(showList);
System.out.println(shows);
课程。
Show
我的public class Show {
private int showId;
private int siteId;
private String name;
private int duration;
private int providerId;
private List<Events> events;
//getters and setters
@Override
public String toString() {
return "Show{" +
"showId=" + showId +
", siteId=" + siteId +
", name='" + name + '\'' +
", duration=" + duration +
", providerId=" + providerId +
", events=" + events +
'}';
}
}
班级
Events