How to implement deserialization so that the resulting objects use the common Ingredient from the List.

public class Blueprint { private String name; private List<Ingredient> ingredients; } 

Full code:

 List<Ingredient> ingredients = new ArrayList<Ingredient>(); ingredients.add(new Ingredient("Water", 1)); ingredients.add(new Ingredient("Flour", 1)); Blueprint bread = new Blueprint("Bread", ingredients); Blueprint pellet = new Blueprint("Pellet", ingredients); String breadJson = convertToJson(bread); String pelletJson = convertToJson(pellet); Blueprint restoredBread = loadFromJSon(breadJson); Blueprint restoredPellet = loadFromJSon(pelletJson); System.out.println(restoredBread); System.out.println(restoredPellet); 

Conclusion:

 Blueprint{name='Bread', ingredients=[Ingredient@402f32ff, Ingredient@573f2bb1]} Blueprint{name='Pellet', ingredients=[Ingredient@5ae9a829, Ingredient@6d8a00e3]} 

In the current form, respectively, Jackson creates new ingredients for each drawing, and I would like him to take the drawings from the map.

    1 answer 1

    The following solution has now been found: Use getInstance in Ingredient, thus ensuring uniqueness.

     private static Map<String, Ingredient> ingredients = new HashMap<String, Ingredient>(); @JsonCreator public static Ingredient getInstance(@JsonProperty("name") String name, @JsonProperty("volume") double volume) { if (ingredients.containsKey(name)) return ingredients.get(name); else { Ingredient created = new Ingredient(name, volume); ingredients.put(name, created); return created; } }