0

I have a similar question to Jackson dynamic property names. I need to set the result property name according to the value of var_name. What can I do in the custom serializer, if anything, to pass var_name?

@NotBlank
private String var_name;    
@NotNull
private Object result;
public DataObject(String var_name, Object result) {
    this.var_name = var_name;
    this.result = result;
}
@JsonProperty
@JsonSerialize(using = CustomSerializer.class)
public String getName() {
    return var_name;}
@JsonProperty
@JsonSerialize(using = CustomSerializer.class)
public void setName(Object var_name) {
    this.result = var_name;}    
@JsonProperty
@JsonSerialize(using = CustomSerializer.class)
public Object getResult() {
    return result;}
@JsonProperty
@JsonSerialize(using = CustomSerializer.class)
public void setResult(Object result) {
    this.result = result;}

public class CustomSerializer extends JsonSerializer<Object> {
    public void serialize(Object value, JsonGenerator jgen,    SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeObjectField(***how can i insert var_name here***, value);
        jgen.writeEndObject();
    }
}

Post call:

@POST
public List<DataObject> search(){   
    List<DataObject> list = new ArrayList<DataObject>();
    //some iteration function
        //...
        list.add(new DataObject(variable_string, variable_object));   
        //...      
    return list;
}

Where variable_string and variable_object are define by the result of a query to a knowledge base.
Desired json response example:

[{
    "Name": "John",
    "Age": 69
},
{
    "Name": "Jane",
    "Gender": "Female",
    "DateTime": "2017-6-12T15:09:25"
}]

Thanks.

wmw301
  • 49
  • 1
  • 8

1 Answers1

2

For the situation you mentioned in your question, you could use a Map<K, V>:

@POST
public List<Map<String, String>> search() {   

    List<Map<String, String>> list = new ArrayList<>();
    Map<String, String> item;

    item = new HashMap<>();
    item.put("Name", "John");
    item.put("Age", "69");
    list.add(item);

    item = new HashMap<>();
    item.put("Jane", "John");
    item.put("Age", "96");
    list.add(item);

    return list;
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • Ok. I've explained it worng. It should be `list.add(new DataObject(variable_string, variable_object));` where `variable_string` and `variable_object` are define by the result of a query to a knowledge base. – wmw301 Jun 12 '17 at 12:41
  • @wmw301 You could use a `Map` then. – cassiomolin Jun 12 '17 at 12:43
  • can the Map be used with keys like the ones in the edited json response? I'll try this, and will report in a bit. – wmw301 Jun 12 '17 at 13:21
  • Indeed using a list of maps made the trick (although I had tried using a Map before and failed due to the duplicate key restriction, never remembered to use List>) Thanks – wmw301 Jun 12 '17 at 13:33