Spring MVC控制器中的JSON参数 [英] JSON parameter in spring MVC controller

查看:119
本文介绍了Spring MVC控制器中的JSON参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

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

我传递了profileJson这个方式:

I pass profileJson this way:

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

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

but my profileJson object has all null fields. What should I do to make spring parse my json?

推荐答案

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

This could be done with a custom editor, that converts the JSON into a UserProfile object:

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);
    }
}

这是用于在控制器类中注册编辑器:

This is for registering the editor in the controller class:

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

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

And this is how to use the editor, to unmarshall the JSONP parameter:

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

这篇关于Spring MVC控制器中的JSON参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆