Spring MVC:自定义JSON响应

时间:2017-02-09 14:57:53

标签: java json spring-mvc

我有一个返回

的RestController方法
// The method which builds custom JSON response from retrieved data
public List<HashMap<String, Object>> queryTasks() {
        return buildResponse(...);
}

随着时间的推移,响应变得越来越大,需要搜索,过滤等附加功能,并且使用hashmap进行操作变得更加困难。 我现在想使用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一样?

1 个答案:

答案 0 :(得分:1)

您可以使用自定义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();
    }
}