How to deserialize a JSON array of objects using Gson library?

前端 未结 1 1444
抹茶落季
抹茶落季 2020-12-14 09:14

I am facing an issue while I am trying to deserialize a JSON array of objects using the Gson library.

An example of the JSON array:

[
    {\"ID\":1,\         


        
相关标签:
1条回答
  • 2020-12-14 09:22

    To deserialize a JSONArray you need to use TypeToken. You can read more about it from GSON user guide. Example code:

    @Test
    public void JSON() {
        Gson gson = new Gson();
        Type listType = new TypeToken<List<MyObject>>(){}.getType();
        // In this test code i just shove the JSON here as string.
        List<Asd> asd = gson.fromJson("[{'name':\"test1\"}, {'name':\"test2\"}]", listType);
    }
    

    If you have a JSONArray then you can use

    ...
    JSONArray jsonArray = ...
    gson.fromJson(jsonArray.toString(), listType);
    ...
    
    0 讨论(0)
提交回复
热议问题