如何使用GSON将JSON数组序列化为Java对象?

时间:2014-09-03 20:24:06

标签: java json 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并在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 $

我在这里做错了什么?

1 个答案:

答案 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);