我在这里有点迷失,
我有一个像这样的JSON字符串:
{
"type":"fuu",
"message":"bar",
"data":{
"5":{
"post":"foo",
"type":"bar",
},
"0":{
"post":"foo",
"type":"bar",
},
"1":{
"post":"foo",
"type":"bar",
},
// and so on...
}
}
请问如何使用Gson将其解析为POJO? (我需要获取对象列表)
我对对象列表元素前面的数字感到有点困惑....
答案 0 :(得分:2)
试试这个 -
<强> Pojo.java 强>
import java.util.Map;
public class Pojo {
private String type;
private String message;
private Map<Integer, InnerPojo> data;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Map<Integer, InnerPojo> getData() {
return data;
}
public void setData(Map<Integer, InnerPojo> data) {
this.data = data;
}
@Override
public String toString() {
return "Pojo [type=" + type + ", message=" + message + ", data=" + data
+ "]";
}
}
<强> InnerPojo.java 强>
public class InnerPojo {
private String type;
private String post;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
@Override
public String toString() {
return "InnerPojo [type=" + type + ", post=" + post + "]";
}
}
<强> Main.java 强>
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Pojo;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
public static void main(String[] args) {
String j = "{\"type\": \"fuu\", \"message\": \"bar\", \"data\":{ \"0\":{\"post\": \"foo\", \"type\": \"bar\"}, \"1\":{\"post\": \"foo\", \"type\": \"bar\"}, \"5\":{\"post\": \"foo\", \"type\": \"bar\"}}}";
Pojo p = gson.fromJson(j, Pojo.class);
System.out.println(p);
}
}
结果是 -
Pojo [type=fuu, message=bar, data={0=InnerPojo [type=bar, post=foo], 1=InnerPojo [type=bar, post=foo], 5=InnerPojo [type=bar, post=foo]}]
答案 1 :(得分:0)
对于valueHasMutated
部分,我会尝试将其解析为"data"
结构,有关说明,请参阅this thread。