I am trying to parse a json data file that has a singular object inside two different ArrayLists:
{
"TA": [
{
"firstname": "John",
"lastname": "Smith"
},
{
"firstname": "Jane",
"lastname": "Doe"
}
],
"Student": [
{
"firstname": "John",
"lastname": "Smith"
},
{
"firstname": "Kevin",
"lastname": "White"
}
]
}
My current parsing method just creates a new Person object for each one and adds them to each List object, but I want my Person object John Smith to only be a singular object referenced by both "TA" list and "Student" list. How could I go about doing this?
CodePudding user response:
TA and Student list are two different list. If you define each list and populate them with the same object (person), yes they would point to the same object. That is object oriented approach.
Parsing a Json and expecting to have the same person object in both arrays is not possible (assuming that person object would get created by the parser). The parser would process each array individually and hence you person object is not going to be the same.
There is a way you can do it that would be by defining person object in a static class. This way you would always get the same instance of the person object.
I your case you will have to create a static person object for each variants (firstname lastname)
CodePudding user response:
If you're trying to lower memory usage, you can use a static factory method to intern instances. Assuming you use Jackson:
class Person {
private static Map<Person, Person> cache = new HashMap<>();
@JsonCreator
public static Person create(String firstname, String lastname) {
Person person = new Person(firstname, lastname);
return cache.computeIfAbsent(person, Function.identity());
}
final String firstname;
final String lastname;
private Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
@Override
public boolean equals(Object o) {
return o instanceof Person
&& Objects.equals(((Person)o).firstname, this.firstname)
&& Objects.equals(((Person)o).lastname, this.lastname);
}
// hashCode override...
}