Skip to content

Instantly share code, notes, and snippets.

@guigonzalezz
Last active June 11, 2022 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guigonzalezz/fcd8724ce0075efcb486763c067565c2 to your computer and use it in GitHub Desktop.
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
@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