2

I need to create json where the objects are all structured similarly, but can contain different object names, i.e.:

    "obj1":{
         "field1":1,
         "field2":2
     }
    "obj2":{
         "field1":4,
         "field2":5
     }
    "obj3":{
         "field1":7,
         "field2":8
     }

How can I use jackson to create dynanic field names? this would be done during run time depending on input taken

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kaylee
  • 145
  • 1
  • 10
  • possible duplicate of [Jackson dynamic property names](http://stackoverflow.com/questions/12134231/jackson-dynamic-property-names) – Sam Berry Jul 07 '15 at 14:27

1 Answers1

2

You could possibly refer to this answer: Jackson dynamic property names.

Basically you can use a custom JsonSerializer.

  @JsonProperty("p")
  @JsonSerialize(using = CustomSerializer.class)
  private Object data;

  // ...

public class CustomSerializer extends JsonSerializer<Object> {
  public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeObjectField(value.getClass().getName(), value);
    jgen.writeEndObject();
  }
}
Community
  • 1
  • 1
m.mitropolitsky
  • 125
  • 2
  • 10