[英]How to serialize JSON array to a Java Object using GSON?
我有一个下面的JSON文档,我需要解析。 我只在files
数组中显示两个对象。 通常,我将有500多个对象。
{
"files":[
{
"name":"/testing01/partition_395.shard",
"max_chain_entries":20,
"partition":"297, 298",
"new_users":"123, 345, 12356"
},
{
"name":"/testing02/partition_791.shard",
"max_chain_entries":20,
"partition":"693, 694, 695",
"new_users":"3345, 6678, 34568"
}
]
}
这是我上面对象的DataModel类-
public class JsonResponseTest {
private String name;
private String max_chain_entries;
private String partition;
private String new_users;
// getters here
}
我需要提取所有的new_users
如果name
标签有/testing01
并填充它HashSet
在Java中。 我正在使用GSON进行JSON序列化。
private static RestTemplate restTemplate = new RestTemplate();
private static final Gson gson = new Gson();
public static void main(String[] args) {
String jsonResponse = restTemplate.getForObject(
"some_url", String.class);
Type collectionType = new TypeToken<List<JsonResponseTest>>() {}.getType();
List<JsonResponseTest> navigation = gson.fromJson(jsonResponse, collectionType);
System.out.println(navigation);
}
但是上面的代码给我错误信息为-
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
我在这里做错什么了吗?
问题是您首先拥有一个JSON对象,然后拥有JSON数组,但是您反序列化认为它是JSON Array。 尝试下面的代码-
String jsonResponse = restTemplate.getForObject("some_url", String.class);
Type collectionType = new TypeToken<List<JsonResponseTest>>() {}.getType();
JsonObject json = new JsonParser().parse(jsonResponse).getAsJsonObject();
JsonArray jarr = json.getAsJsonObject().getAsJsonArray("files");
List<JsonResponseTest> navigation = gson.fromJson(jarr, collectionType);
System.out.println(navigation);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.