简体   繁体   English

从资源中读取 JSON 文件并在 Java 中创建对象列表

[英]Reading a JSON File from resources and creating a List of Objects in Java

Basically, I have the JSON file below and I need to read him and add into a List of Objects in Java, Which library should I use in this case?基本上,我有下面的 JSON 文件,我需要阅读他并添加到 Java 中的对象列表中,在这种情况下我应该使用哪个库? My biggest difficulty is read the Json starting with the array instead of a normal object, and inside the elements of the first array try to read the other array inside.我最大的困难是从数组而不是普通对象开始读取 Json,并在第一个数组的元素内尝试读取里面的另一个数组。

[
 {
  "name: "Andrew",
  "age": 21, 
  "parents": [
   {
    "name": "Joseph",
    "age": 18
   },
   {
    "name": "Joseph",
    "age": 18
   }
  ]
 },
{
  "name: "Maria",
  "age": 35, 
  "parents": [
   {
    "name": "Kassandra",
    "age": 16
   },
   {
    "name": "Abigail",
    "age": 22
   }
  ]
 }
]

[EDIT 06/11/2022] [编辑 06/11/2022]

I created this github gist below for the answer of this problem, Thank you everyone for the help I appreciate.我在下面创建了这个 github gist 来回答这个问题,谢谢大家的帮助。

Answer: https://gist.github.com/guigonzalezz/fcd8724ce0075efcb486763c067565c2答案: https ://gist.github.com/guigonzalezz/fcd8724ce0075efcb486763c067565c2

There are lots of API's and libraries are present but I prefer to use org.json API suggested by json.org有很多 API 和库,但我更喜欢使用org.json建议的 org.json API

you can also go for GSON library which is one of the best library for serialize and deserialize Java objects to (and from) JSON.您还可以使用 GSON 库,它是用于将 Java 对象序列化和反序列化到(和从)JSON 的最佳库之一。

here's the quick demo of reading above JSON with org.json API.这是使用 org.json API 阅读以上 JSON 的快速演示。

import org.json.JSONObject;
import org.json.JSONArray;

public class HelloWorld {
    public static void main(String[] args) {
        String jsonString = "[ { \"name\": \"Andrew\", \"age\": 21, \"parents\": [ { \"name\": \"Joseph\", \"age\": 18 }, { \"name\": \"Joseph\", \"age\": 18 } ] }, { \"name\": \"Maria\", \"age\": 35, \"parents\": [ { \"name\": \"Kassandra\", \"age\": 16 }, { \"name\": \"Abigail\", \"age\": 22 } ] } ]";
        JSONArray json = new JSONArray(jsonString);
        for(int i=0; i<json.length(); i++){
          JSONObject j = json.getJSONObject(i);
          System.out.println(j + "\n------");
        }
    }
}

Use jackson library.使用杰克逊库。 Here is a snippet.这是一个片段。

public static void main(final String[] args) throws JsonProcessingException {
    final List<Child> children = new ObjectMapper().readValue(
        readFromFile("data.json"), new TypeReference<List<Child>>() {
        });
    System.out.println(children);
  }

  public static String readFromFile(final String resourcePath) {
    final ClassPathResource resource = new ClassPathResource(resourcePath);

    try {
      final InputStream inputStream = resource.getInputStream();
      return readFromInputStream(inputStream);
    } catch (final IOException var4) {
      return "";
    }
  }

  private static String readFromInputStream(final InputStream inputStream) throws IOException {
    final StringBuilder resultStringBuilder = new StringBuilder();
    final BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    Throwable var3 = null;

    try {
      String line;
      try {
        while ((line = br.readLine()) != null) {
          resultStringBuilder.append(line).append("\n");
        }
      } catch (final Throwable var12) {
        var3 = var12;
        throw var12;
      }
    } finally {
      if (br != null) {
        if (var3 != null) {
          try {
            br.close();
          } catch (final Throwable var11) {
            var3.addSuppressed(var11);
          }
        } else {
          br.close();
        }
      }

    }

    return resultStringBuilder.toString();
  }

Google's gson seems the easiest most concise route to go.谷歌的 gson 似乎是最简单最简洁的路线。 It already has a serializer/deserializer that should work for most pojos out of the box.它已经有一个序列化器/反序列化器,应该适用于大多数开箱即用的 pojo。

    String json = "[ { \"name\": \"Andrew\", \"age\": 21, \"parents\": [ { \"name\": \"Joseph\", \"age\": 18 }, { \"name\": \"Joseph\", \"age\": 18 } ] }, { \"name\": \"Maria\", \"age\": 35, \"parents\": [ { \"name\": \"Kassandra\", \"age\": 16 }, { \"name\": \"Abigail\", \"age\": 22 } ] } ]";

    //default deserializer should work for strings, wrappers and select generics(including list)
    Gson gson = new Gson();

    JsonArray jsonArray = gson.fromJson(json, JsonArray.class);

    for (JsonElement jsonElement : jsonArray) {
        Person iPerson = gson.fromJson(jsonElement, Person.class);
        System.out.println(iPerson);
    }
    //output       
 /*  Person{name='Andrew', age=21, parents=[Person{name='Joseph', age=18, parents=null}, Person{name='Joseph', age=18, parents=null}]}
Person{name='Maria', age=35, parents=[Person{name='Kassandra', age=16, parents=null}, Person{name='Abigail', age=22, parents=null}]}*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM