I use Jackson 2.9.8
用于转换我的下面POJO
as JSON
:
public class ResponseEntity implements Serializable {
private static final long serialVersionUID = 1L;
private int total_record_count;
private int filtered_record_count;
@JsonProperty("list")
private List<Map<String,Object>> entityList;
public ResponseEntity(List<Map<String,Object>> entityList) {
this.entityList = entityList;
this.filtered_record_count = entityList.size();
}
public int getTotal_record_count() {
return total_record_count;
}
public void setTotal_record_count(int total_record_count) {
this.total_record_count = total_record_count;
}
public int getFiltered_record_count() {
return filtered_record_count;
}
public void setFiltered_record_count(int filtered_record_count) {
this.filtered_record_count = filtered_record_count;
}
public List<Map<String, Object>> getEntityList() {
return entityList;
}
public void setEntityList(List<Map<String, Object>> entityList) {
this.entityList = entityList;
}
}
结果中JSON
, 的价值实体列表成员映射到list键,如其注释所示@JsonProperty("list")
:
{
"list" : [ {
"id" : "IID000000002129959",
"attr1" : "MY",
"attr2" : "sd",
"attr3" : true }]
}
但我需要用不同的名称来定制它。对于某些响应应该是busines1
, business2
, etc.
我该如何制作JsonProperty
名字动态?
您可以在构造函数中提供名称并使用JsonAnyGetter。以下解决方案:
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws Exception {
ResponseEntity entity = new ResponseEntity("dynList",
Collections.singletonList(Collections.singletonMap("key", "value1")));
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(mapper.writeValueAsString(entity));
}
}
class ResponseEntity implements Serializable {
private static final long serialVersionUID = 1L;
private int total_record_count;
private int filtered_record_count;
private String propertyName;
@JsonIgnore
private List<Map<String, Object>> entityList;
public ResponseEntity(String propertyName, List<Map<String, Object>> entityList) {
this.propertyName = propertyName;
this.entityList = entityList;
this.filtered_record_count = entityList.size();
}
@JsonAnyGetter
public Map<String, Object> otherProperties() {
return Collections.singletonMap(propertyName, entityList);
}
// other methods
}
prints:
{
"total_record_count" : 0,
"filtered_record_count" : 1,
"dynList" : [ {
"key" : "value1"
} ]
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)