简体   繁体   中英

Spring MVC: customise JSON response

I have a RestController method which returns

// 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:

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.

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).

How I can dynamically build response like in my first case with 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:

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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