[英]Using GSON on Android to parse JSON data
I am trying to use the Gson to parse the following JSON data: 我正在尝试使用Gson解析以下JSON数据:
[
{
"idRed":1,
"nombre":"XXXX",
"imagen":"XXXXX.png",
"imagenPublica":"XXXXX.png",
"grupos":[
{
"idGrupo":-1,
"nombre":"Todos"
},
{
"idGrupo":1,
"nombre":"Principal"
}
]
},
...
]
I have two entities to encapsulate the JSON data: 我有两个实体来封装JSON数据:
public class Red implements Parcelable {
@SerializedName("idRed")
private long idRed = 0;
@SerializedName("nombre")
private String nombre = "";
@SerializedName("imagen")
private String url = "";
@SerializedName("grupos")
private ArrayList<Grupo> grupos = new ArrayList<Grupo>();
//getters and setters
}
And: 和:
public class Grupo implements Parcelable {
@SerializedName("idGrupo")
private long idGrupo = 0;
@SerializedName("idRed")
private long idRed = 0;
@SerializedName("nombre")
private String nombre = null;
//getters and setters
}
And finally I have this code to parse the JSON data: 最后,我有以下代码来解析JSON数据:
Gson gson = new Gson();
List<Red> redes = (List<Red>) gson.fromJson(result, new TypeToken<List<Red>>() {}.getType());
I can see my JSON in variable result
, but the program throws an exception. 我可以在变量
result
看到我的JSON,但是程序抛出异常。
Can you see any bugs in my code? 您可以在我的代码中看到任何错误吗?
First: Add a root to your json. 首先:向您的json添加根。 You can do it by string operation after you've fetched this json by post/get.
通过post / get获取此json后,可以通过字符串操作来实现。
{
result: [
{
"idRed":1,
"nombre":"XXXX",
"imagen":"XXXXX.png",
"imagenPublica":"XXXXX.png",
"grupos":[
{
"idGrupo":-1,
"nombre":"Todos"
},
{
"idGrupo":1,
"nombre":"Principal"
}
]
},
...
]
}
Add a new class for root, the rest classes could still be used. 为root添加一个新类,其余类仍可以使用。
public class Result implements Parcelable {
@SerializedName("result")
private ArrayList<Red> grupos = new ArrayList<Red>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.