如何从restful json webservice返回动态字段

时间:2016-04-27 10:25:48

标签: rest spring-mvc jackson

我使用Sprint MVC和jackson jar创建了restful json webservice。 我的控制器看起来像这样: -

@Controller
public class AdminController {

@RequestMapping(value = "/fetchMyData", method = RequestMethod.POST)   
public @ResponseBody MyResponse getDynamicResponse(@RequestBody UserRequest userRequest) {                       

    MyResponse myResponse = someDAO.calldatabase("userRequest) ");
return myResponse; 
}

然而,现在我的消费者不希望所有的字段都响应,因为我们有大约150个字段,他们一次需要2或3个字段。他们将在请求中发送字段列表,我将只需要相同的字段。

所以现在有时我的输出应该是: -

{
"field1": "someValue",
"field2": "someOtherValue"
}

其他时间会是: -

{
"field1": "someValue",
"field2": "someOtherValue",
"field3": "someOtherValue"
}

使用一些静态注释,如 @JSONIgnore @JsonIgnoreProperties(ignoreUnknown = true,value = {“field1”})不是选项,因为它会每次硬编码。

我可以通过扩展来尝试覆盖来自Jackson的类 ObjectMapper 的方法,但是不确定如何在序列化期间将我的类告诉Spring MVC?

最简单的解决方法是我可以使用注释 @JsonInclude(Include.NON_NULL)但是我无法在响应中发送null吗?

在运行时从我的Spring MVC restful webservice实现返回动态字段数的想法或方法吗?

0 个答案:

没有答案
相关问题