我需要序列化以下类:
@JsonSerialize(using = ItemSerializer.class)
public class Project {
@JsonProperty
public Map<String, Field> fields = new HashMap<String, Field>();
}
Field类:
public class Field {
public String name;
@JsonIgnore
public boolean isStringField;
public Field(String name, boolean isStringField) {
this.name = name;
this.isStringField = isStringField;
}
}
序列化功能:
@Override
public void serialize(...) throws ... {
jgen.writeStartObject();
for(Map.Entry<String, Field> entry : value.fields.entrySet()){
if(entry.getValue().isStringField){
jgen.writeStringField(entry.getKey(), entry.getValue().name);
}else{
jgen.writeObjectField(entry.getKey(), entry.getValue());
}
}
jgen.writeEndObject();
JSON我得到的几乎就是我需要的东西:
{
"fieldValue4": {
"name": "field4"
},
"fieldValue3": {
"name": "field3"
},
"fieldValue2": {
"name": "field2"
},
"fieldValue1": "field1"
}
除了名为 fileds 的父元素(来自Project类的变量名)不在此JSON中。如何将其添加到结果JSON中以获得类似:
{
"fields": {
"fieldValue4": {
"name": "field4"
},
"fieldValue3": {
"name": "field3"
},
"fieldValue2": {
"name": "field2"
},
"fieldValue1": "field1"
}
}
答案 0 :(得分:2)
由于您已经指定了自己的自定义序列化程序,因此在序列化gen.writeObjectFieldStart("fields");
地图之前只需指定fields