Deserialize Map key as POJO reference

  • 0
  • Pump00:00

Is it possible in Jackson to get a reference to a previously-deserialized object from the same json string given it’s id?

For example, I have the following Java classes:

public class Company {
    List<Employee> employeeList;
    List<Customer> customerList;
    ....
}

@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
public class Customer {
    Long id;
    ...
}

public class Employee {
    Long id;
    Map<Customer, int> utilityMap;
    ...
}

I want to create a Company instance from a json string that looks like:

{
  "customerList" : [ {
    "id" : 0,
    "name" : "customer0"
  } ],
  "employeeList" : [ {
    "id" : 1,
    "fullName" : "employee0",
    "utilityMap" : {
      "0" : 1
    }
  } ]
}

where the key 0 in utilityMap refers to the customer with id 0.

With KeyDeserializer I’m able to create a new Customer object, but I want the Map’s key to be a reference to the corresponding object instead.

A simple solution would be to change the signature of Map<Customer, int> to be Map<Long, int>, but this not possible due to internal dependencies, is there another way to accomplish this without changing the model (similar to xml references)?

Default Asked on February 6, 2020 in Programming.
Add Comment
  • 0 Answer(s)
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.