使用GSON将JSON转换为POJO
我正在尝试使用GSON将JSON对象转换为POJO。虽然我没有得到任何错误/异常,但包装器类中的列表对象最终仍然为空。知道我做错了什么吗 JSON字符串使用GSON将JSON转换为POJO,json,gson,pojo,Json,Gson,Pojo,我正在尝试使用GSON将JSON对象转换为POJO。虽然我没有得到任何错误/异常,但包装器类中的列表对象最终仍然为空。知道我做错了什么吗 JSON字符串 { "location":[ { "id":"1", "locationName":"Location 1", "eventType":[ { "id":"1", "eventName"
{
"location":[
{
"id":"1",
"locationName":"Location 1",
"eventType":[
{
"id":"1",
"eventName":"Event 1"
},
{
"id":"2",
"eventName":"Event 2"
},
{
"id":"3",
"eventName":"Event 3"
}
]
},
{
"id":"2",
"locationName":"Location 2",
"eventType":[
{
"id":"4",
"eventName":"Event 4"
},
{
"id":"5",
"eventName":"Event 5"
},
{
"id":"6",
"eventName":"Event 6"
}
]
},
{
"id":"3",
"locationName":"Location 3",
"eventType":[
{
"id":"7",
"eventName":"Event 7"
},
{
"id":"8",
"eventName":"Event 8"
},
{
"id":"9",
"eventName":"Event 9"
}
]
}
]
}
与GSON一起使用的包装器类
public class LocationWrapper {
public List<Location> locationList;
public List<Location> getLocationList() {
return locationList;
}
public void setLocationList(List<Location> locationList) {
this.locationList = locationList;
}
}
我使用的方法
private void parseGSONfile(String fileName) {
Gson gson = new Gson();
//getting string from file, you can insert the above string here
String json = new JSONParser().getJSONStringFromFile(fileName);
List<Location> locationList;
LocationWrapper locationWrapper = null;
try {
locationWrapper = gson.fromJson(json, LocationWrapper.class);
} catch (Exception e) {
}
//here the contained object locationList is still null
locationList = locationWrapper.getLocationList();
}
private void parseGSONfile(字符串文件名){
Gson Gson=新的Gson();
//从文件中获取字符串,可以在此处插入上面的字符串
String json=new JSONParser().getJSONStringFromFile(文件名);
列表位置列表;
LocationWrapper LocationWrapper=null;
试一试{
locationWrapper=gson.fromJson(json,locationWrapper.class);
}捕获(例外e){
}
//此处包含的对象locationList仍然为空
locationList=locationWrapper.getLocationList();
}
您的json为字段location
提供了一个值,但是您的类LocationWrapper
得到了一个名为locationList
的字段,因此该字段不匹配。重命名字段或使用@SerializedName
是的,就是这样,我在列表中的Location类中也有相同的错误。谢谢
public class EventType {
private long id;
private String eventName;
public EventType() {
}
public EventType(long id, String eventName) {
this.id = id;
this.eventName = eventName;
}
public EventType(int id, String eventName) {
this.id = id;
this.eventName = eventName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
}
private void parseGSONfile(String fileName) {
Gson gson = new Gson();
//getting string from file, you can insert the above string here
String json = new JSONParser().getJSONStringFromFile(fileName);
List<Location> locationList;
LocationWrapper locationWrapper = null;
try {
locationWrapper = gson.fromJson(json, LocationWrapper.class);
} catch (Exception e) {
}
//here the contained object locationList is still null
locationList = locationWrapper.getLocationList();
}