Issue
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
Solution
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------");
}
}
}
Answered By - Kishor Mandve
Answer Checked By - Mary Flores (JavaFixing Volunteer)