【问题标题】:How to use Gson to parse a list of json objects with nested arrays如何使用 Gson 解析带有嵌套数组的 json 对象列表
【发布时间】:2015-04-23 20:32:04
【问题描述】:

我是 Gson 的新手,对 java 不是很熟悉。我有一个 json 对象列表,然后在每个对象中列出如下:

[
  {
    "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"
  }
]

如果您能详细或分步回答如何执行此操作以及使用哪些类和方法,我将不胜感激。

【问题讨论】:

    标签: java list gson


    【解决方案1】:

    您是否已经尝试过任何东西(网上已经有很多示例可用)?

    使用谷歌“https://github.com/google/gson”库。

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

    所以现在创建一个类似于 JSON 结构的 Java POJO。

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

    现在使用 GSON 库来解析字符串。

     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);
        }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多