简体   繁体   中英

JSON - serialize only “values” of the Map using Jackson

In my Data transfer object, I have a declaration

private Map<Long, StateDomain> stateDomains;

If you just serialize this to JSON, you will get

{
  stateDomains:[{"key1": stateDomain1}, {"key2": stateDomain2}...]
}

that I do not want . Instead, I want it to become

{
  stateDomains:[{stateDomain1}, {stateDomain2}...]
}

that is, to serialize only values of this map as a List, and discarding pairing with Long keys.

How could this be best achieved with Jackson?

There are two ways to perform this action:

  1. Dirty way:

Change getter of stateDomains to return only Collection of StateDomain :

Eg:

public Collection<StateDomain> getStateDomains() {
        return stateDomains.values();
 }
  1. Create a custom serializer for Map:

Eg:

class CustomSerializer extends JsonSerializer<Map<Long, StateDomain>> {
    @Override
    public void serialize(final Map<Long, StateDomain> value, final JsonGenerator jgen, final SerializerProvider provider)
            throws IOException, JsonProcessingException {
        jgen.writeObject(value.values());
    }
}

Add serializer in DTO:

@JsonSerialize(using = CustomSerializer.class)
private Map<Long, StateDomain> stateDomains;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM