Last active
June 11, 2022 23:16
-
-
Save guigonzalezz/fcd8724ce0075efcb486763c067565c2 to your computer and use it in GitHub Desktop.
Reading a JSON starting with a Array of Objects using org.json on SpringBoot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Service | |
public class JsonService{ | |
private final String MyJSON = "C:/Put your file path here"; | |
private List<Person> people = new ArrayList<Person>(); | |
@Autowired | |
public JsonService() { | |
try { | |
Path filePath = Path.of(MyJSON); | |
String jsonString = Files.readString(filePath); | |
JSONArray json = new JSONArray(jsonString); | |
for(int i=0; i<json.length(); i++){ | |
JSONObject jsonPerson = json.getJSONObject(i); | |
Person person = new Person(); | |
person.setName(jsonPerson.get("name")); | |
person.setAge(jsonPerson.get("age")); | |
JSONArray jsonArrayParents = new JSONArray(jsonPerson.get("parents")); | |
for(int y=0; y< jsonArrayParents.length(); y++) { | |
JSONObject jsonParent = jsonArrayParents.getJSONObject(y); | |
Person parent = new Person(); | |
parent.setName(jsonParent.get("name")); | |
parent.setAge(jsonParent.get("age")); | |
person.getParents().add(parent); | |
} | |
this.people.add(person); | |
} | |
} catch (JSONException | IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
class Person { | |
private String name; | |
private Integer age; | |
private List<Person> parents; | |
//getters and setters | |
} | |
// JSON EXAMPLE | |
// [ | |
// { | |
// "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 | |
// } | |
// ] | |
// } | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment