Spring rest controller result wrapping with JsonView / MappingJacksonValue

时间:2016-04-18 10:44:07

标签: json spring jackson spring-web

I have a Spring API that allows the user to specify the JsonView of each call using a view param like so:

/api/v1/person/1?view=viewName

I then use Spring's MappingJacksonValue to set the correct view dynamically instead of using @JsonView() annotation and finally I just return the MappingJacksonValue instance which produces something along the lines of

[
    { id: 1 },
    { id: 2 }
]

I can't for the life of me figure out how to easily wrap my MappingJacksonValue instances in an ObjectNode so that I can change all API results from the snippet above to this

{
    "data" : [
        { id: 1 },
        { id: 2 }
    ]
}

I tried using a regular HashMap<> but that didn't work - the serialization completely ignores the MappingJacksonValue view and it also produces Map-specific results

{
    data: {
        value: [],
        serializationView: "com.blah.models.view.View$Id",
        filters: null,
        jsonpFunction: null
    }
}

So can someone pls let me know what's the best way to achieve result wrapping in my scenario?

Thanks in advance!

1 个答案:

答案 0 :(得分:1)

如果有人发现这篇文章想要做同样的事情,我意识到我正在以错误的方式看待问题。我最终创建了一个ServiceResponse类,并将对象包装在那里

public class ServiceResponse {

    @JsonView(View.Id.class)
    private Object data;

    public ServiceResponse (Object data) {
        this.data = data;
    }
}

所以基本上不是返回new MappingJacksonValue(someReturnObject)而是返回new MappingJacksonValue(new ServiceResponse(someReturnObject))。这样,所有内容都可以很好地包装在data JSON对象中,而setSerializationView方法仍可以正确过滤我的对象。

希望这有助于某人。