Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make two different ArrayLists reference the same object when Parsing a Json file

Tags:

java

json

parsing

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?

like image 856
Will Avatar asked Sep 17 '26 01:09

Will


1 Answers

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);
    }
}
like image 118
shmosel Avatar answered Sep 19 '26 14:09

shmosel