-1

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

3
  • Gson is a good library. <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.9.0</version> </dependency> Commented Jun 11, 2022 at 6:06
  • Try this - stackoverflow.com/questions/25346512/… Commented Jun 11, 2022 at 6:54
  • I would recommend the API suggested by json.org. Here is the link: github.com/stleary/JSON-java Commented Jun 11, 2022 at 7:21

3 Answers 3

1

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------");
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I used your answer to create a solution for my specifc case, with this JSONArray and JSONObject i was able to manipulate my json in the way i want, and i used the Path class to find my file, i will create a Github Gist with the result if someone have the same problem can solve this easily. Thank you soo much.
0

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

1 Comment

I tried your solution but when i use the ObjectMapper().readValue i got an error saying that the TypeReference is wrong. And I replace this 2 methods for a single line using the java.nio.file.Path, i will create a Github Gist with the result if someone have the same problem can solve this easily.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.