CommanderData
CommanderData

Reputation: 585

Jackson JSON - Serialize same object with different logic

Imagine you have an object A with many fields where one field is an id which uniquely identifies this object. In my java code there is an object B which holds these objects in several data structures similar to this code:

private List<A> all;
private Map<Long, A> mapped;

Now when serializing B to json I only want that objects A in list all are serialized with all fields and those in map mapped only with the id field. How would you do that?

Upvotes: 1

Views: 509

Answers (1)

contrapost
contrapost

Reputation: 693

You can implement StdConverter interface:

public class YourConverter implements StdConverter<Map<Long, A>, Map<Long, String>> {
  @Override
  public Map<Long, String> convert(final Map<Long, A> inMap) {
    final HashMap<Long, String> outMap = new HashMap<>();
    inMap.forEach((k, v) -> outMap.put(k, v.getId()));
    return outMap;
    // Or as one-liner
    // return inMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getId()));
  }
}

Then you can add your converter as JsonSerialize annotation:

private List<A> all;
@JsonSerialize(converter = YourConverter.class)
private Map<Long, A> mapped;

Upvotes: 1

Related Questions