0

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!

4

1 回答 1

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))。这样,所有内容都很好地包装在dataJSON 对象中,并且该setSerializationView方法仍然可以正确过滤我的对象。

希望这可以帮助某人。

于 2016-04-19T11:15:17.040 回答