在没有模型的Java中使用GSON解析JSON文件

yyyllmsg  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(176)

我尝试使用GSON解析JSON文件,其结构如下:

[
   {
      "datasetid":"geonames-postal-code@public-us",
      "recordid":"2d026c84998f913f0f0f5dd9f0d17ab0f78f5c44",
      "fields":{
         "longitude":"18.3475",
         "coordinates":[
            54.1486,
            18.3475
         ],
         "admin_name1":"Pomerania",
         "admin_name2":"Gda\u0144sk County",
         "admin_name3":"Przywidz",
         "postal_code":"83-041",
         "admin_code3":"220405",
         "country_code":"PL",
         "admin_code1":"82",
         "latitude":"54.1486",
         "admin_code2":"2204",
         "place_name":"Sucha Huta",
         "accuracy":"6"
      }
   },
   {
      "datasetid":"geonames-postal-code@public-us",
      "recordid":"c5f689d377a9a460d3b06b772fc621088484e719",
      "fields":{
         "longitude":"18.505",
         "coordinates":[
            54.2232,
            18.505
         ],
         "admin_name1":"Pomerania",
         "admin_name2":"Gda\u0144sk County",
         "admin_name3":"Pruszcz Gda\u0144ski",
         "postal_code":"83-041",
         "admin_code3":"220404",
         "country_code":"PL",
         "admin_code1":"82",
         "latitude":"54.2232",
         "admin_code2":"2204",
         "place_name":"\u017bu\u0142awka",
         "accuracy":"6"
      }
   }
]

我只需要阅读“字段”中的值。我已经在互联网上找遍了,我所能看到的都是在类/模型中操作的示例。
没有课堂和榜样,我怎么读书?

BufferedReader br = null;
Gson gson = new Gson();
br = new BufferedReader(new FileReader("C:\\res\\postal_codes.json"));
bqujaahr

bqujaahr1#

最简单的方法是使用Gson的默认解析函数Gson#fromJson(String json, Type typeOfT)
我提供了一些值,您可以将其作为示例打印出来。

Reader reader = new BufferedReader(new FileReader("C:\\res\\postal_codes.json"));
JsonArray jsonElements = new Gson().fromJson(reader, JsonArray.class);
for (JsonElement jsonElement : jsonElements) {
    JsonObject item = jsonElement.getAsJsonObject();
    // Write datasetid.
    String datasetid = item.get("datasetid")
            .getAsString();
    System.out.println("Dataset ID: " + datasetid);
    // Write recordid.
    String recordid = item.get("recordid").getAsString();
    System.out.println("Record ID: " + recordid);
    // Write country_code.
    JsonObject fields = item.getAsJsonObject("fields");
    System.out.println("Country Code: " + fields.get("country_code").getAsString());
    // Write coordinates.
    JsonArray coordinates = fields.getAsJsonArray("coordinates");
    System.out.println("Coordinates: " + coordinates.toString());
}

**注意:**最好的方法是使用POJO。我建议您关注它,但出于某种原因,如果您不想使用它,它也会起作用。

相关问题