Kaylee
Kaylee

Reputation: 145

Getting dynamic property names with jackson

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

Upvotes: 2

Views: 5181

Answers (1)

m.mitropolitsky
m.mitropolitsky

Reputation: 125

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();
  }
}

Upvotes: 2

Related Questions