FasterXML / jackson-docs

Documentation for the Jackson JSON processor.
719 stars 111 forks source link

custom serialization of map attributes #5

Closed amnonkhen closed 8 years ago

amnonkhen commented 8 years ago

I have an object with a map attribute with nested keys, e.g.

I need it to be serialized to JSON in a flattened manner, i.e.:

{
  "k1.nested11": "value11",
  "k1.nested12": "value12",
  "k2.nested21": "value11",
  "k2.nested22": "value22",
}

Is there anyway to achieve this without using custom serialization to the entire object? I thought of some combination of @JsonAnyGetter and @JsonSerialize, but it does not work.

Here's what I tried in my custom serializer for the Map property:

    @Override
    public void serialize(Map<String, Object> map, 
                           JsonGenerator jgen, 
                          SerializerProvider provider) 
                throws IOException, JsonProcessingException
 {
        map.forEach((k, v) -> {
            try {
                jgen.writeObjectField(k, v);
            } catch (IOException e) {
                logger.warn("problem serializing field [" + k + "] with value [" + v+"]", e);
            }
        });
    }

I am getting the following error message:

2016-09-05 10:51:08,348 [main] WARN  MapJsonSerializer - problem writing field [swapLegs.1.nested1_k1] with value [nested1_v1]
com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value
    at com.fasterxml.jackson.core.base.GeneratorBase._reportError(GeneratorBase.java:412)
    at com.fasterxml.jackson.core.json.WriterBasedJsonGenerator.writeFieldName(WriterBasedJsonGenerator.java:195)
    at com.fasterxml.jackson.core.JsonGenerator.writeObjectField(JsonGenerator.java:1018)

Am I using jgen.writeObjectField(k, v) incorrectly? Can I call it a few times and add several properties?

cowtowncoder commented 8 years ago

Please use user mailing list for user question.