[英]Parsing json with nested arrays with Gson
我是Gson解析的新手,并且做了很少的基本Gson解析。 但这次我的JSON非常复杂。 我的JSON看起来像:
{"uname":"man101",
"uid":"2",
"account":{
"entry":[8,15.48],
"exit":[8,15.48],
"details":
[[0,0],[0,8.2],[1.15,8.2],[1.15,18.23],[7.33,18.23],[7.33,15.48],[12.15,2.28],
[12.35,2.28],[12.35,0],[10.65,0],[10.65,1.42],[8.1,1.42],[8.1,3.95],
[4.25,3.95],[4.25,0]],
"section":
[
{
"account":[[0,0],[0,3.35],
[4.25,3.35],[4.25,0]],
"category":"office",
"description":"Mobile based company",
"sectionname":"xyz",
"id":1
},
{
"account":[[0,3.95],[0,7.8],
[4.25,7.8],4.25,3.95]],
"category":"office",
"description":"Network based company",
"sectionname":"ABC",
"id":2
},
]
},
"category":"Cowork",
"description":"Combined office space"
}
我试图通过以下方式解析它
public class AccountData
{
public String uname;
public String uid;
public String category;
public String description;
public Account account;
public class Account
{
public float[] entry;
public float[] exit;
public List<float[]> details;
public List<Section> section;
}
public class Section
{
public List<float[]> account;
public String category;
public String description;
public String sectionname;
public String id;
}
}
并尝试传递这样的结果
Gson gson = new Gson();
beaconList = gson.fromJson(result, AccountData.class);
它运行时没有任何错误,但是当我尝试访问某些数据时,它会提供空值。
首先 ,您的JSON是错误的,这是更正的版本(请注意,例如代码第9行中的额外逗号)。
{
"uname": "man101",
"uid": "2",
"account": {
"entry": [
8,
15.48
],
"exit": [
8,
15.48
],
"details": [
[
0,
0
],
[
0,
8.2
],
[
1.15,
8.2
],
[
1.15,
18.23
],
[
7.33,
18.23
],
[
7.33,
15.48
],
[
12.15,
2.28
],
[
12.35,
2.28
],
[
12.35,
0
],
[
10.65,
0
],
[
10.65,
1.42
],
[
8.1,
1.42
],
[
8.1,
3.95
],
[
4.25,
3.95
],
[
4.25,
0
]
],
"section": [
{
"account": [
[
0,
0
],
[
0,
3.35
],
[
4.25,
3.35
],
[
4.25,
0
]
],
"category": "office",
"description": "Mobile based company",
"sectionname": "xyz",
"id": 1
},
{
"account": [
[
0,
3.95
],
[
0,
7.8
],
[
4.25,
7.8
],
[
4.25,
3.95
]
],
"category": "office",
"description": "Network based company",
"sectionname": "ABC",
"id": 2
}
]
},
"category": "Cowork",
"description": "Combined office space"
}
您可以使用http://json.parser.online.fr/或http://www.bodurov.com/JsonFormatter/查看您的json。
其次 ,Gson不喜欢内部类,除非它们被声明为静态。
第三 :避免在类中混合数组和泛型,泛型使用起来更安全,所以我重新定义了您的类,如下所示:
public class AccountData {
public String uname;
public String uid;
public String category;
public String description;
public Account account;
public static class Account {
public List<Double> entry;
public List<Double> exit;
public List<List<Double>> details;
public List<Section> section;
}
public static class Section {
public List<List<Double>> account;
public String category;
public String description;
public String sectionname;
public String id;
}
}
如果您不喜欢内部静态类,则可以始终将Section
和Account
放入单独的文件中(当然,不使用静态关键字)。
编辑
正如Brian Roach在评论中指出的那样,内部类不再需要静态与Gson一起工作。 所以第2点不再是真的,你可以从类声明中删除静态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.