使用Gson的JSON解析 [英] JSON parsing using Gson
问题描述
我试图用GSON解析一个JSON对象。
我的JSON是:
{truncate:[
{
lower:20,
upper:40,
delimiter:,
scope:[$ title] $
lower:30,
upper:65,
分隔符:
}
] }
我已经定义了我的2个类:
public class TruncateObj {
private List< TruncateObjectChild> objChild;
// getter and setter
}
和 p>
public class TruncateObjectChild {
private int lower;
private int upper;
私人字符串分隔符;
私人列表< String>范围;
// getters and setters
}
我的分析语句
Gson gson = new Gson();
TruncateObj truncation = gson.fromJson(template,TruncateObj.class);
由于某些原因,这不起作用。 Gson创建一个 TruncatObj
子元素,但TruncateObj中的 List< TruncateObjectChild>
为null。
我在做什么错?
字段
与它在JSON中的名称不匹配。将字段重命名为 TruncateObj
中的objChild truncate
,然后再试一次。 另外,您可以注释 objChild 字段用
@SerializedName(truncate)
告诉gson使用 truncate $ c中的值JSON中的$ c>字段作为Java对象中的
objChild
字段的值。
I am trying to parse a JSON object using GSON.
My JSON is :
{ "truncate": [
{
"lower": 20,
"upper": 40,
"delimiter": " ",
"scope": ["$title"]
},
{
"lower": 30,
"upper": 65,
"delimiter": " "
}
] }
I have defined my 2 classes like:
public class TruncateObj {
private List<TruncateObjectChild> objChild;
// getter and setter
}
and
public class TruncateObjectChild {
private int lower;
private int upper;
private String delimiter;
private List<String> scope;
// getters and setters
}
My Parsing statement is
Gson gson = new Gson();
TruncateObj truncation = gson.fromJson(template, TruncateObj.class);
For some reason this is not working. Gson creates a TruncatObj
child, but the List<TruncateObjectChild>
within the TruncateObj is null.
What is wrong in what I am doing?
The field objChild
in your TruncateObj
does not match the name it has in the JSON. Rename the field to truncate
and try again.
Alternatively, you could annotate the objChild
field with an @SerializedName("truncate")
to tell gson to use the value from the truncate
field in the JSON as the value for the objChild
field in your Java object.
这篇关于使用Gson的JSON解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!