Jackson JSON List with Object Type

前端 未结 3 795
广开言路
广开言路 2020-12-31 09:53

I have to serialize JSON from a list of Objects. The resulting JSON has to look like this:

{
    \"status\": \"success\",
    \"models\": [
        {
                


        
3条回答
  •  一生所求
    2020-12-31 10:29

    Another approach is using StdConverter class. Here is a working (abbreviated) example:

    // MyParentObject.java
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
    import com.fasterxml.jackson.databind.annotation.JsonSerialize;
    
    public class MyParentObject {
      @JsonSerialize(converter = ChildListToString.class)
      @JsonDeserialize(converter = StringToChildList.class)
      @JsonProperty
      public List myChildren;
    }
    
    // ChildListToString.java
    
    import com.fasterxml.jackson.databind.util.StdConverter;
    
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class ChildListToString extends StdConverter, String> {
      @Override
      public String convert(List value) {
        // this is just as effective as using Jackson "write array"
        // Try-Catch omitted for brevity
        StringBuilder builder = new StringBuilder("[");
        value.stream().map(value -> new ObjectMapper().writeValue(value)).forEach(urnStr -> {
          if(builder.length() > 1) {
            builder.append(", ");
          }
    
          builder.append("\"").append(urnStr).append("\"");
        });
    
        builder.append("]");
    
        return builder.toString();
      }
    }
    
    // StringToChildList.java
    
    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.util.StdConverter;
    
    
    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.util.Collections;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class StringToChildList extends StdConverter> {
    
      @Override
      public List convert(String value) {
        // try - catch omitted here for brevity
          List strings = new ObjectMapper().readValue(value, new TypeReference>() {});
          return strings.stream()
              .map(string -> {
                return new ObjectMapper().readValue(string, AChildObject.class)
              }).collect(Collectors.toList());
    
      }
    }
    

    I like this because it gives you control of serialization and deserialization separately.

提交回复
热议问题