java - Spring MVC Controller 中的JSON参数

我有

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

我这样传递profileJson:

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

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

最佳答案

解决这个问题的方法非常简单,实际上会让你发笑,但在我开始之前,让我先强调一下,任何有自尊的 Java 开发人员都不会,我的意思是永远在不使用 JSON 的情况下工作Jackson 高性能 JSON 库。

Jackson 不仅是 Java 开发人员的工作马和事实上的 JSON 库,而且它还提供了一整套 API 调用,使 JSON 与 Java 的集成变得轻而易举(您可以在 http://jackson.codehaus.org/ 下载 Jackson)。

现在来回答。假设您有一个看起来像这样的 UserProfile pojo:

public class UserProfile {

private String email;
// etc...

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

// more getters and setters...
}

...然后您的 Spring MVC 方法将 GET 参数名称“profileJson”转换为 JSON 值为 {"email": "mymail@gmail.com"} 在您的 Controller 中将如下所示:

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper; // this is your lifesaver right here

//.. your controller class, blah blah blah

@RequestMapping(value="/register", method = RequestMethod.GET) 
public SessionInfo register(@RequestParam("profileJson") String profileJson) 
throws JsonMappingException, JsonParseException, IOException {

    // now simply convert your JSON string into your UserProfile POJO 
    // using Jackson's ObjectMapper.readValue() method, whose first 
    // parameter your JSON parameter as String, and the second 
    // parameter is the POJO class.

    UserProfile profile = 
            new ObjectMapper().readValue(profileJson, UserProfile.class);

        System.out.println(profile.getEmail());

        // rest of your code goes here.
}

砰!你完成了。我鼓励你仔细阅读 Jackson API 的大部分内容,因为正如我所说,它是救命稻草。例如,您是否从 Controller 返回 JSON?如果是这样,您需要做的就是在您的库中包含 JSON,并返回您的 POJO,Jackson 将自动将其转换为 JSON。没有比这更容易的了。干杯! :-)

https://stackoverflow.com/questions/21577782/

相关文章:

java - 使用 gson 反序列化对象的特定 JSON 字段

ruby - 将不间断空格转换为 Ruby 中的空格

java - 如何从 JSON 对象中获取日期

json - 使用绝对或相对路径在 curl 请求中发送 json 文件

ios - swift: 将多个 对象添加到 NSDictionary

java - 我如何反序列化以 jackson 为单位的时间戳?

python - 将 JSON 日期字符串转换为 Python 日期时间

c# - 如何将 IEnumerable 转换为 JSON?

c# - 在 JSON.NET 中序列化/反序列化字节数组

java - 对象序列化为 JSON(使用 Gson)。如何在 UpperCamelCase 中设置