简体   繁体   English

Spring MVC:自定义JSON响应

[英]Spring MVC: customise JSON response

I have a RestController method which returns 我有一个RestController方法,它返回

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

In course of time the response became bigger, additional features like search, filtering was required and operating with hashmap become harder. 随着时间的流逝,响应会变得越来越大,需要其他功能(例如搜索,过滤),并且使用哈希图进行操作会变得更加困难。 I want to use DTO for this response now, but there was one feature with 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 response was dynamically build tree for domain entities with not null parents. JSON响应是为具有非空父级的域实体动态构建的树。

Doing it in DTO will lead to creating variable for each parent entity and populating them with null (It's possible to have 5 levels of parent-child entities). 在DTO中执行此操作将导致为每个父实体创建变量并将其填充为null(可能有5个级别的父子实体)。

How I can dynamically build response like in my first case with HashMap? 我如何像在第一种情况下那样使用HashMap动态构建响应?

You can use a custom Jackson serializer for this, writing either a null value or the actual parent object using the correct property name: 您可以为此使用自定义的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM