我有一个我需要解析的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
并在Java中用HashSet
填充它。我正在使用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 $
我在这里做错了什么?
答案 0 :(得分:2)
问题是你首先拥有一个JSON对象,然后是JSON数组,但是你反序列化认为它是JSON数组。请尝试以下代码 -
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);