[英]GSON to parse a JSON array
I have a JSON file like this: 我有一个像这样的JSON文件:
[
{
"id": "1",
"name": "test1",
"childrens": [
{
"id": "14",
"name": "test2",
"childrens": [
]
}
]
}
]
The model class: 模型类:
public class Model {
private int id;
private String name;
}
And my parse method: 而我的解析方法:
public List< Model > parseJSONService(JSONArray jsonArray) {
Gson gson = new Gson();
Model[] model = gson.fromJson(jsonArray.toString(),
Model[].class);
return Arrays.asList(model);
}
why not parse the json string directly? 为什么不直接解析json字符串? this is what i did, achieved the same thing you looking for i guess: 这就是我所做的,实现了您正在寻找的相同功能,我猜:
public class GsonPlay {
public static void main(String args[]) {
String testString = "[{\"id\": \"1\",\"name\": \"test1\",\"childrens\": [{\"id\": \"14\",\"name\": \"test2\",\"childrens\": []}]}]";
List<Model> modelList = parseJsonService(testString);
System.out.println(modelList);
}
private static List<Model> parseJsonService(String testString) {
Gson gson = new Gson();
Model[] models = gson.fromJson(testString, Model[].class);
return Arrays.asList(models);
}
}
class Model {
private int id;
private String name;
private List<Model> childrens;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Model> getChildrens() {
return childrens;
}
public void setChildrens(List<Model> childrens) {
this.childrens = childrens;
}
}
You can also have a look at this for further ideas: 您也可以看看这个进一步的想法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.