[英]Spring MVC: customise JSON response
我有一个RestController方法,它返回
// The method which builds custom JSON response from retrieved data
public List<HashMap<String, Object>> queryTasks() {
return buildResponse(...);
}
随着时间的流逝,响应会变得越来越大,需要其他功能(例如搜索,过滤),并且使用哈希图进行操作会变得更加困难。 我现在想对此响应使用DTO,但是hashmap有一个功能:
AbstractProcessEntity parentDomainEntity = domainEntity.getParent();
do {
if (parentDomainEntity != null) {
taskMap.put(parentDomainEntity.getClass().getSimpleName() + "Id", parentDomainEntity.getId()); parentDomainEntity = parentDomainEntity.getParent();
} else {
taskMap.put("parentDomainEntityId", null);
}
} while (parentDomainEntity != null);
JSON响应是为具有非空父级的域实体动态构建的树。
在DTO中执行此操作将导致为每个父实体创建变量并将其填充为null(可能有5个级别的父子实体)。
我如何像在第一种情况下那样使用HashMap动态构建响应?
您可以为此使用自定义的Jackson序列化程序,使用正确的属性名称写入null
值或实际的父对象:
public class ProcessEntitySerializer extends StdSerializer<ProcessEntity> {
...
@Override
public void serialize(ProcessEntity entity, JsonGenerator jgen,
SerializerProvider provider) throws IOException, JsonProcessingException {
gen.writeStartObject();
if (entity.getParentDomainEntity() == null) {
// No parent, write null value for ID
jgen.writeNullField("parentDomainEntityId");
} else {
// Parent is known, write it as an object
jgen.writeObjectField(entity.getParentDomainEntity().getClass().getSimpleName(),
entity.getParentDomainEntity());
}
// TODO: since you're using a custom serializer, you'll need to serialize any additional properties of the entity manually
// or use the Schema exposed by the base class StdSerializer
jgen.writeEndObject();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.