简体   繁体   中英

How to serialize a map with enum keys in declaration order with JSON?

I have some enum class, let's imagine

public enum MyEnum {
    ONE("one"), TWO("two"), THREE("three"), DEFAULT("some value")
    //..
}

and Dto class:

@JsonPropertyOrder(value = {"id", "name", "params"})
public Dto {
    private Long id;
    private String name;
    private Map<MyEnum, Object> params;
}

How can I setup order for keys in params map? I know that LinkedHashMap can be used to setup order and just add to map in proper order. But! There are cases, when key-value should be added in runtime and it should be added to params map not to last link, but inside map. eg

params = new LinkedHashMap();
params.put(ONE, new String("object1"));
params.put(THREE, new String("object #3"));

and than in another place of code we just added

params.put(TWO, new Integer(20));

and order inside json should be:

{
 "id":"123", "name":"some name", 
"params":{"ONE":"object1","TWO":"20","THREE":"object #3"}
 }

I can suggest two options that both rely on the fact that Jackson uses a MapSerializer to serialize objects of type Map .

First, since enum types define an implicit natural order based on their declaration order, you can enable your ObjectMapper 's SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS . The javadoc states,

Feature that determines whether java.util.Map entries are first sorted by key before serialization or not: if enabled, additional sorting step is performed if necessary (not necessary for java.util.SortedMap s), if disabled, no additional sorting is needed.

In other words, the enums within your params map will first be sorted by their declaration order and only then serialized. Note that this serialization feature applies to all maps.

Second, you can initialize params as an EnumMap . To serialize a Map , MapSerializer iterates the map's entrySet() . The entry set returned by EnumMap#entrySet() is ordered by the declaration order of the constants in the corresponding enum type. You'd have

params = new EnumMap<>(MyEnum.class);
params.put(THREE, new String("object #3"));
params.put(ONE, new String("object1"));
// whatever order

and Jackson will serialize them in the order the enum constants are declared.

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