当前位置: 首页 > 面试题库 >

Spring MVC控制器中的JSON参数

欧阳哲
2023-03-14
问题内容

我有

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
SessionInfo register(UserProfile profileJson){
  ...
}

我以这种方式传递profileJson:

http://server/url?profileJson={"email": "mymail@gmail.com"}

但是我的profileJson对象具有所有空字段。我应该怎么做才能使spring解析我的json?


问题答案:

这可以通过自定义编辑器完成,该编辑器将JSON转换为UserProfile对象:

public class UserProfileEditor extends PropertyEditorSupport  {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        ObjectMapper mapper = new ObjectMapper();

        UserProfile value = null;

        try {
            value = new UserProfile();
            JsonNode root = mapper.readTree(text);
            value.setEmail(root.path("email").asText());
        } catch (IOException e) {
            // handle error
        }

        setValue(value);
    }
}

这是为了在控制器类中注册编辑器:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(UserProfile.class, new UserProfileEditor());
}

这是使用编辑器解组JSONP参数的方法:

@RequestMapping(value = "/jsonp", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
SessionInfo register(@RequestParam("profileJson") UserProfile profileJson){
  ...
}


 类似资料:
  • 我有过 我通过这种方式传递profileJson: 但是我的配置文件Json对象具有所有空字段。我应该怎么做才能让Spring解析我的json?

  • 我一直在尝试使用: 使用此链接: 但我有一个错误: 当我换成: 是工作。我能做些什么来和日期一起工作? 谢啦

  • 我正在使用Spring形式。我只需要得到Staemap作为响应,但我得到的是整个jsp页面作为响应。

  • 问题内容: 我正在阅读一本书,并在有关控制器的一章中谈到渲染的内容,对于JSON,它有一个类似这样的示例,但没有详细介绍,因此我无法弄清楚该示例所适合的整体情况: 还有使用JSONP和回调函数的示例: 有人可以解释这些吗? 问题答案: 通常,您将返回JSON的原因之一是: A)您正在将部分/全部应用程序构建为单页应用程序(SPA),并且需要客户端JavaScript能够提取其他数据而无需完全重新加

  • 我正在寻找重定向与参数到一个控制器在Laravel和拿起参数在第二个控制器。 我是按照下面链接的文档在第一个控制器中设置的。 https://laravel.com/docs/5.3/redirects#redirecting-控制器动作 重定向 路线 第二控制器 但是,这当前返回未定义的变量。 这是最好的方法吗?如果是的话,我错在哪里?

  • 问题内容: 我刚刚开始学习Angular.js,并且一直在Angular主页上的“连接后端”示例中查看project.js。 我对控制器功能中的参数感到困惑: 这些控制器函数在routeProvider中调用,但未给出任何参数。 我能找到到目前为止,这可能解释发生了什么事情的唯一的事情是“注入服务整合到控制器”,这说明,而不是参数的方法和。 我的具体问题是: 控制器参数是什么? 带有参数的控制器功