Jackson JSON List with Object Type

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

    There's no built-in way to do this. You'll have to write your own JsonSerializer. Something like

    class ModelSerializer extends JsonSerializer> {
    
        @Override
        public void serialize(List value, JsonGenerator jgen,
                SerializerProvider provider) throws IOException {
            jgen.writeStartArray();
            for (Model model : value) {
                jgen.writeStartObject();
                jgen.writeObjectField("model", model);
                jgen.writeEndObject();    
            }
            jgen.writeEndArray();
        }
    
    }
    

    and then annotate the models field so that it uses it

    @JsonSerialize(using = ModelSerializer.class)
    private List models;
    

    This would serialize as

    {
        "status": "success",
        "models": [
            {
                "model": {
                    "id": 1,
                    "color": "red"
                }
            },
            {
                "model": {
                    "id": 2,
                    "color": "green"
                }
            }
        ]
    }
    

    If you're both serializing and deserializing this, you'll need a custom deserializer as well.

提交回复
热议问题