这是我尝试使用Gson解析的Json响应。但是我在创建java类时遇到了麻烦,我将从json方法传递给它。有人可以帮我吗?
{
"id":5,
"name":"1322",
"number":"1",
"polygons":[
[
[
[-122.00895192246342,37.41167155605386],
[-122.0089070066992,37.41181283360041],
[-122.0087533947856,37.411780725090495],
[-122.00879741223456,37.411636593387556],
[-122.00895192246342,37.41167155605386]
],
0,
"#11d4a0",
"A Zone Name"
]
]
}
答案 0 :(得分:0)
这种数据结构可能更有意义:
{
"id":5,
"name":"1322",
"number":"1",
"polygons":[
{
[
[-122.00895192246342,37.41167155605386],
[-122.0089070066992,37.41181283360041],
[-122.0087533947856,37.411780725090495],
[-122.00879741223456,37.411636593387556],
[-122.00895192246342,37.41167155605386]
],
0,
"#11d4a0",
"A Zone Name"
}
]
}
答案 1 :(得分:0)
使用以下课程:
public class Example {
private int id;
private String name;
private String number;
private List<List<Object>> polygons;
}
<强>测试强>
String json = "{\"id\":5,\"name\":\"1322\",\"number\":\"1\"," + "\"polygons\":[[[[-122.00895192246342,37.41167155605386]," + "[-122.0089070066992,37.41181283360041],"
+ "[-122.0087533947856,37.411780725090495]," + "[-122.00879741223456,37.411636593387556]," + "[-122.00895192246342,37.41167155605386]]," + "0," + "\"#11d4a0\"," + "\"A Zone Name\"]]}";
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Example example = gson.fromJson(json, Example.class);
验证解决方案:
内部列表将被反序列化为一个对象,该对象可能是您的示例json的另一个List或String或Double值。循环遍历该列表并获取值。例如:
for (int i = 0; i < example.polygons.get(0).size(); i++) {
Object polygon = example.polygons.get(0).get(i);
if (polygon instanceof List) {
for (int j = 0; j < ((List) polygon).size(); j++) {
Object innerArray0 = ((List) polygon).get(j);
System.out.print("Item#" + i + "." + j);
if (innerArray0 instanceof List) {
for (int k = 0; k < ((List) innerArray0).size(); k++) {
Object value = ((List) innerArray0).get(k);
System.out.print(" : value[" + k + "] :" + value + " ");
}
}
System.out.println("");
}
} else if (polygon instanceof Double || polygon instanceof String) {
System.out.println("Item#" + i + " : value : " + polygon);
}
System.out.println("");
}
System.Out:
Item#0.0 : value[0] :-122.00895192246342 : value[1] :37.41167155605386
Item#0.1 : value[0] :-122.0089070066992 : value[1] :37.41181283360041
Item#0.2 : value[0] :-122.0087533947856 : value[1] :37.411780725090495
Item#0.3 : value[0] :-122.00879741223456 : value[1] :37.411636593387556
Item#0.4 : value[0] :-122.00895192246342 : value[1] :37.41167155605386
Item#1 : value : 0.0
Item#2 : value : #11d4a0
Item#3 : value : A Zone Name