简体   繁体   中英

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? 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.

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

I created this github gist below for the answer of this problem, Thank you everyone for the help I appreciate.

Answer: 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

you can also go for GSON library which is one of the best library for serialize and deserialize Java objects to (and from) JSON.

here's the quick demo of reading above JSON with org.json API.

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. It already has a serializer/deserializer that should work for most pojos out of the box.

    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}]}*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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