假设我们有这样的JSON对象:
{
"employees" : {
"Mike" : 23,
"Bill" : 42,
"Jimmy" : 30
}
}
接下来的课程:
public class Employees {
private List<Employee> employees;
}
public class Employee {
private String name;
private int age;
}
我们有没有办法将json反序列化为Employees类型对象?
答案 0 :(得分:1)
List可用于反序列化元素数组[...]
,但{...}
是对象。如果您愿意,可以考虑使用Map
代替List
class Data {
Map<String,String> employees;
}
...
Gson gson = new Gson();
Data data = gson.fromJson(json, Data.class);
for (Map.Entry<String, String> emp: data.employees.entrySet())
System.out.println(emp.getKey()+" -> "+emp.getValue());
输出:
Mike -> 23
Bill -> 42
Jimmy -> 30
如果您想使用这些类解析您的json
public class Employees {
private List<Employee> employees;
}
public class Employee {
private String name;
private int age;
}
您的数据应如下所示:
{
"employees" : [
{"name":"Mike", "age": 23},
{"name":"Bill", "age": 42},
{"name":"Jimmy", "age": 30}
]
}
答案 1 :(得分:0)
您可以使用Jackson
&#39; ObjectMapper
类来反序列化JSON,如下所示:https://stackoverflow.com/a/6349488/2413303