Jackson JSON List with Object Type

前端 未结 3 812
广开言路
广开言路 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:45

    This is an oldish question, But there is an arguably more idiomatic way of implementing this (I'm using jackson-databind:2.8.8):

    Define a ModelSerializer (That extends StdSerializer as recommended by Jackson) that prints your model how you like and use the @JsonSerialize(contentUsing = ...) over your collection type:

    class ModelSerializer extends StdSerializer {
    
        public ModelSerializer(){this(null);}
        public ModelSerializer(Class t){super(t);} // sets `handledType` to the provided class
    
        @Override
        public void serialize(List value, JsonGenerator jgen,
                SerializerProvider provider) throws IOException,
                JsonProcessingException {
            jgen.writeStartObject();
            jgen.writeObjectField("model", value);
            jgen.writeEndObject();
        }
    }
    

    Meanwhile, in another file:

    class SomethingWithModels {
        // ...
        @JsonSerialize(contentUsing = ModelSerializer.class)
        private Collection models;
        // ...
    }
    

    Now you aren't bound to just Lists of models but may apply this to Collections, Sets, Native []s and even the values of Maps.

提交回复
热议问题