簡體   English   中英

Spring MVC:自定義JSON響應

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM