简体   繁体   中英

Serialize/Deserialize custom Map<Key, Object> in Jackson

I have a pretty simple Map I want to serialize and deserialize in Jackson, but I can't get it to work.

I have tried the following:

@JsonSerialize(keyUsing=TurnKeySerializer.class)
@JsonDeserialize(keyUsing = TurnKeyDeserializer.class)
Map<TurnKey, PlayerTurn> publicTurns = new TreeMap<>();

@JsonIgnoreProperties(ignoreUnknown = true)
@Data //Creates Getter/Setter etc
public class TurnKey implements Comparable<TurnKey> {
    private final int turnNumber;
    private final String username;

    public TurnKey(int turnNumber, String username) {
        this.turnNumber = turnNumber;
        this.username = username;
    }

    @Override
    public int compareTo(TurnKey o) {
        int v = Integer.valueOf(turnNumber).compareTo(o.getTurnNumber());
        if (v != 0) {
            return v;
        }
        return username.compareTo(o.getUsername());
    }

    @Override
    public String toString() {
        return "{" +
                "turnNumber:" + turnNumber +
                ", username:'" + username + "'" +
                "}";
    }


public class TurnKeySerializer extends JsonSerializer<TurnKey> {
    @Override
    public void serialize(TurnKey value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        if (null == value) {
            throw new IOException("Could not serialize object to json, input object to serialize is null");
        }
        StringWriter writer = new StringWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer, value);
        gen.writeFieldName(writer.toString());
    }
}


public class TurnKeyDeserializer extends KeyDeserializer {
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public TurnKey deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return mapper.readValue(key, TurnKey.class);
    }

}

But I get an exception

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token

You need to define/override the fromString() method in TurnKey. Jackson will use toString() to serialize and fromString() to deserialize. That's what "Can not find a (Map) Key deserializer" means in the error message Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not find a (Map) Key deserializer for type [simple type, class no.asgari.civilization.server.model.TurnKey] at com.fasterxml.jackson.databind.deser.DeserializerCache._handleUnknownKeyDeserializer(DeserializerCache.java:584) .

A custom KeyDeserializer is not needed.

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