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?
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(
@JsonProperty("firstname") String firstname,
@JsonProperty("lastname") 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);
}
@Override
public int hashCode() {
return Objects.hash(this.firstname, this.lastname);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With