How to use Gson to parse a list of json objects with nested arrays

自闭症网瘾萝莉.ら 提交于 2019-12-14 03:33:50

问题


I am new to Gson and not very experienced with java. I have a list of json objects and then lists inside each object like this:

[
  {
    "A": 358584,
    "B": "Apache",
    "C": [
      "Ethnicity",
      "Ethnicity in fiction",
      "American Indian group"
    ],
    "D": 23.647824738317627,
    "E": "Ethnicity",
    "F": "Apache"
  },
  {
    "A": 19283806,
    "B": "San Jose",
    "C": [
      "Location",
      "Employer",
      "Region",
      "Transit Service Area"
    ],
    "D": 11.184500611578535,
    "E": "Location",
    "F": "San Francisco Bay Area"
  }
]

I would appreciate a detailed or step by step answer on how to do this and which classes and methods to use.


回答1:


Did you try anything already (There are plenty of examples already availalbe online)?

Use google 'https://github.com/google/gson' library.

JSON format: <Attribute_Name> : <Value>
[] --> List or Array
{} --> Single Object

So now create a Java POJO just like JSON structure.

class Data {
    private Integer A;
    private String B;
    private List<String> C;
    private Double D;
    private String E;
    private String F;
    }

Now use the GSON library to parse the string.

 public static void main(String[] args) {
    String data = "[{\"A\":358584,\"B\":\"Apache\",\"C\":[\"Ethnicity\",\"Ethnicity in fiction\",\"American Indian group\"],\"D\":23.647824738317627,\"E\":\"Ethnicity\",\"F\":\"Apache\"},{\"A\":19283806,\"B\":\"San Jose\",\"C\":[\"Location\",\"Employer\",\"Region\",\"Transit Service Area\"],\"D\":11.184500611578535,\"E\":\"Location\",\"F\":\"San Francisco Bay Area\"}]";

    Data[] dataArray = (new Gson()).fromJson(data, Data[].class);
    if (dataArray != null) {
        System.out.println(dataArray.length);
    }
    }


来源:https://stackoverflow.com/questions/29833749/how-to-use-gson-to-parse-a-list-of-json-objects-with-nested-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!