0

Assume, I have the following structure:

public class SomeClass {
private String id;
@JsonProperty("key-value")
private Map<String, Object> keyValue;}

Obviously, it will be serialized to

 {
   "id" : "id1", 
   "key-value" : 
    {"key1" : "value1",
    "key2 : "value2"}
 }

Is it possible to represent it like this?

 {
   "id" : "id1", 
   "key1" : "value1",
   "key2 : "value2"
 }

Thanks in advance!

  • so with the new question here http://stackoverflow.com/questions/33799243/jsonanygetter-doesnt-work I understand that you aren't really interested in this question nor its answer?? – Sharon Ben Asher Nov 19 '15 at 09:47
  • @sharonbn, I had tried to create the new question BEFORE you have answered me. But stackoverflow said me that it will be possible only 90 minutes later the creation of the previous one. And honestly, I don't know why that question was created. Your solution works correctly. Thank you! – Arseny Istlentyev Nov 19 '15 at 10:12
  • perhaps stackoverflow put the 90 min restriction for a reason? anyway, if my solution works correctly, please show the appriciation by accepting the answer. – Sharon Ben Asher Nov 19 '15 at 10:26

1 Answers1

1

It is quite possible with the help of Jackson's custom serializer:

  1. add the @JsonSerialize annoation to your POJO:

(also added necessary ctor and getters)

@JsonSerialize(using = SomeClassSerializer.class)
public static class SomeClass {
    private String id;
    @JsonProperty("key-value")
    private Map<String, Object> keyValue;

    public SomeClass(String id, Map<String, Object> keyValue) {
        this.id = id;
        this.keyValue = keyValue;
    }
    public String getId() { return id; }
    public Map<String, Object> getKeyValue() { return keyValue; }
}
  1. the custom serializer looks like this:

:

public class SomeClassSerializer extends JsonSerializer<SomeClass>
{
    @Override
    public void serialize(SomeClass sc, JsonGenerator gen, SerializerProvider serializers)
            throws IOException, JsonProcessingException
    {
        gen.writeStartObject();
        // write id propertry
        gen.writeStringField("id", sc.getId());   
        // loop on keyValue entries, write each as property
        for (Map.Entry<String, Object> keyValueEntry : sc.getKeyValue().entrySet()) {
            gen.writeObjectField(keyValueEntry.getKey(), keyValueEntry.getValue());
        }
        gen.writeEndObject();
    }
}
  1. calling Jackson's mapper is done in the usual manner:

:

public static void main(String[] args)
{
    Map<String, Object> keyValue = new HashMap<>();
    keyValue.put("key1", "value1");
    keyValue.put("key2", "value2");
    keyValue.put("key3", new Integer(10));
    SomeClass sc = new SomeClass("id1", keyValue);

    try {
        new ObjectMapper().writeValue(System.out, sc);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

output:

{"id":"id1","key1":"value1","key2":"value2","key3":10}
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47