Reputation: 49
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.
Upvotes: 0
Views: 2618
Reputation: 130917
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;
}
Upvotes: 2