我有

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

我是这样通过的:

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

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

推荐答案

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

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

@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){
  ...
}

Json相关问答推荐

JSON字符串处理注入引号

震击:三针并用震击

如何在数组抖动中按值分组

解析SQL中的嵌套JSON

如何在改装Android中将ResponseBody转换为JSONObject

JQ-JSON将键转换为对象

用巨大的值更新SQL Server中的nvarchar(max)

在 SQL 存储过程中使用参数 Select 值

Jolt 规范将父对象中的所有键应用于数组中的所有对象

使用 jq 从字符串列表开始创建对象

用于遮蔽卡的 Jolt 规格

派生类的属性没有得到价值

如果值不存在,则将值插入 JSON 数组

如何为所有 API 端点全局设置 http.ResponseWriter Content-Type 标头?

哪个更好:Json 或 XML (PHP)

在 JavaScript 中从 Json 数据中删除反斜杠

Java JSON 序列化 - 最佳实践

将 PHP 结果数组转换为 JSON

如何创建 JSON 对象 Node.js

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?