【问题标题】:Custom json in SpringSpring中的自定义json
【发布时间】:2010-07-21 09:13:53
【问题描述】:

我已经在 Spring 3 应用程序中配置了 ContentNegotiatingViewResolver,因此当我使用看起来像 **.json 的 URL 调用控制器时,它会使用 jackson 库返回一个 json 对象。

如果我调用这个方法:

@RequestMapping("/myURL.json")
public List<MyClass> myMethod(){
    List<MyClass> mylist = myService.getList();
    return mylist;
}

在我收到的 JSON 中,我有:

{"myClassList":[
   { object 1 in json },
   { object 2 in json },
   { object 3 in json } ...
 ]
}

我的问题是:¿有什么方法可以配置 json 中使用的名称 myClassList 吗? ¿是否有可能以这种方式生成没有此变量的 json(类似于以下变量)?

[
   { object 1 in json },
   { object 2 in json },
   { object 3 in json } ...
]

谢谢。

【问题讨论】:

    标签: java json spring spring-mvc jackson


    【解决方案1】:

    您可以返回 org.springframework.web.servlet.ModelAndView 对象,而不是直接返回 List 对象。在 modelAndView 对象上,您可以设置键的名称。请参考以下sn-p:

    @RequestMapping("/myURL.json")
    public ModelAndView myMethod(){
        ModelAndView modelAndView = new ModelAndView();
        List<MyClass> mylist = myService.getList();
        modelAndView.addObject("MyClassName", myList);
        return modelAndView;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 2012-09-16
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多