首页 > 解决方案 > Serialize flat object to nested JSON structure

问题描述

Challenge

I have a completely flat (POGO/POJO) object which I need to serialize into a nested JSON structure. Preferably using Jackson annotations and/or a custom Serializer

I'm only interested in serializing from object to JSON, deserializing is not needed.

Example

I would like to turn this class:

class SomeClass {
    @JsonProperty('Business.Name')
    BigDecimal prop1 = 42.0
    @JsonProperty('Other.Nested.Business.Name')
    BigDecimal prop2 = 3.14
}

Into this JSON:

{
  "Other" : {
    "Nested.Business.Name" : 3.14
  },
  "Business.Name" : 42.0
}

Catch 22

The code for the class is auto-generated. I have some influence over the generation, but it needs to be completely flat!

Any help would be much appreciated!

Additional info

I already tried making a custom serializer, but failed to write the nested structure.

class SomeClassSerializer extends StdSerializer<SomeClass> {
    void serialize(SomeClass value, JsonGenerator jgen, SerializerProvider provider) {
        jgen.writeStartObject()
        jgen.writeNumberField("Business.Name", value.prop1)
        //how to write the nested structure
        jgen.writeEndObject()
    }
    ....
}

标签: javajsongroovyjackson

解决方案


Where it says // how to write the nested structure, have you tried something like

   jgen.writeObjectFieldStart("Other")
   jgen.writeNumberField("Nested.BusinessName", value.prop2)
   jgen.writeEndObject()

推荐阅读