Serialization of key / value pairs in Jackson?

I have a class

class Foo { String key; String value; } 

and want to serialize this to "<content of key>":"<content of value>" How can I achieve this (and how to deserialize "myKey":"myVal" into a Foo object?

I tried to use

 @JsonValue public String toString() { return "\"" + key + "\":\"" + value + "\""; } 

But obviously too many quotes end.

 @JsonValue public String toString() { return key + ":" + value; } 

also does not work, as it does not create enough quotes.

+7
source share
1 answer

I found one way that uses JsonSerializer as follows:

 public class PropertyValueSerializer extends JsonSerializer<Foo> { @Override public void serialize(Foo property_value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName(property_value.getKey()); jsonGenerator.writeString(property_value.getValue()); jsonGenerator.writeEndObject(); } 

The Foo class should know about this:

 @JsonSerialize(using = PropertyValueSerializer.class) public class Foo { 

Deserializing is very similar:

 public class PropertyValueDeserializer extends JsonDeserializer<PROPERTY_VALUE> { @Override public Foo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { String tmp = jsonParser.getText(); // { jsonParser.nextToken(); String key = jsonParser.getText(); jsonParser.nextToken(); String value = jsonParser.getText(); jsonParser.nextToken(); tmp = jsonParser.getText(); // } Foo pv = new Foo(key,value); return pv; } 

And this should also be annotated in the Foo class:

 @JsonSerialize(using = PropertyValueSerializer.class) @JsonDeserialize(using = PropertyValueDeserializer.class) public class Foo implements Serializable{ 
+14
source

All Articles