Java spring MVC控制器中的JSON参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21577782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON parameter in spring MVC controller
提问by Stepan Yakovenko
I have
我有
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
SessionInfo register(UserProfile profileJson){
...
}
I pass profileJson this way:
我通过 profileJson 这种方式:
http://server/url?profileJson={"email": "[email protected]"}
but my profileJson object has all null fields. What should I do to make spring parse my json?
但我的 profileJson 对象的所有字段都为空。我该怎么做才能让 spring 解析我的 json?
采纳答案by Angular University
This could be done with a custom editor, that converts the JSON into a UserProfile object:
这可以通过自定义编辑器完成,将 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);
}
}
This is for registering the editor in the controller class:
这是用于在控制器类中注册编辑器:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(UserProfile.class, new UserProfileEditor());
}
And this is how to use the editor, to unmarshall the JSONP parameter:
这是如何使用编辑器解组 JSONP 参数:
@RequestMapping(value = "/jsonp", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
SessionInfo register(@RequestParam("profileJson") UserProfile profileJson){
...
}
回答by Anton Pchelkin
Just add @RequestBody
annotation before this param
只需@RequestBody
在此参数之前添加注释
回答by The Saint
The solution to this is so easy and simple it will practically make you laugh, but before I even get to it, let me first emphasize that no self-respecting Java developer would ever, and I mean EVER work with JSON without utilizing the Hymanson high-performance JSON library.
这个问题的解决方案非常简单,它实际上会让你发笑,但在我开始之前,让我首先强调没有自尊的 Java 开发人员永远不会,我的意思是永远使用 JSON 而不使用 Hymanson high -性能 JSON 库。
Hymanson is not only a work horse and a defacto JSON library for Java developers, but it also provides a whole suite of API calls that makes JSON integration with Java a piece of cake (you can download Hymanson at http://Hymanson.codehaus.org/).
Hymanson 不仅是 Java 开发人员的工作马和事实上的 JSON 库,而且还提供了一整套 API 调用,使 JSON 与 Java 的集成变得轻而易举(您可以在http://Hymanson.codehaus下载 Hymanson 。组织/)。
Now for the answer. Assuming that you have a UserProfile pojo that looks something like this:
现在来看看答案。假设你有一个 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...
}
...then your Spring MVC method to convert a GET parameter name "profileJson" with JSON value of {"email": "[email protected]"} would look like this in your controller:
...然后您的 Spring MVC 方法将 GET 参数名称“profileJson”转换为 JSON 值 {"email": "[email protected]"} 在您的控制器中将如下所示:
import org.codehaus.Hymanson.JsonParseException;
import org.codehaus.Hymanson.map.JsonMappingException;
import org.codehaus.Hymanson.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 Hymanson'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.
}
Bam! You're done. I would encourage you to look through the bulk of Hymanson API because, as I said, it is a lifesaver. For example, are you returning JSON from your controller at all? If so, all you need to do is include JSON in your lib, and return your POJO and Hymanson will AUTOMATICALLY convert it into JSON. You can't get much easier than that. Cheers! :-)
砰!你完成了。我鼓励你浏览大量的 Hymanson API,因为正如我所说,它是一个救星。例如,您是否从控制器返回 JSON?如果是这样,您需要做的就是在您的库中包含 JSON,并返回您的 POJO,Hymanson 会自动将其转换为 JSON。没有比这更容易的了。干杯! :-)
回答by Zigri2612
This does solve my immediate issue, but I'm still curious as to how you might pass in multiple JSON objects via an AJAX call.
这确实解决了我的直接问题,但我仍然很好奇如何通过 AJAX 调用传入多个 JSON 对象。
The best way to do this is to have a wrapper object that contains the two (or multiple) objects you want to pass. You then construct your JSON object as an array of the two objects i.e.
做到这一点的最佳方法是拥有一个包含要传递的两个(或多个)对象的包装器对象。然后,您将 JSON 对象构造为两个对象的数组,即
[
{
"name" : "object1",
"prop1" : "foo",
"prop2" : "bar"
},
{
"name" : "object2",
"prop1" : "hello",
"prop2" : "world"
}
]
Then in your controller method you recieve the request body as a single object and extract the two contained objects. i.e:
然后在您的控制器方法中,您将请求正文作为单个对象接收并提取两个包含的对象。IE:
@RequestMapping(value="/handlePost", method = RequestMethod.POST, consumes = { "application/json" })
public void doPost(@RequestBody WrapperObject wrapperObj) {
Object obj1 = wrapperObj.getObj1;
Object obj2 = wrapperObj.getObj2;
//Do what you want with the objects...
}
The wrapper object would look something like...
包装对象看起来像......
public class WrapperObject {
private Object obj1;
private Object obj2;
public Object getObj1() {
return obj1;
}
public void setObj1(Object obj1) {
this.obj1 = obj1;
}
public Object getObj2() {
return obj2;
}
public void setObj2(Object obj2) {
this.obj2 = obj2;
}
}
回答by deamon
You can create your own Converter
and let Spring use it automatically where appropriate:
您可以创建自己的Converter
并让 Spring 在适当的地方自动使用它:
import com.fasterxml.Hymanson.databind.ObjectMapper;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
class JsonToUserProfileConverter implements Converter<String, UserProfile> {
private final ObjectMapper jsonMapper = new ObjectMapper();
public UserProfile convert(String source) {
return jsonMapper.readValue(source, UserProfile.class);
}
}
As you can see in the following controller method nothing special is needed:
正如您在以下控制器方法中看到的那样,不需要什么特别的:
@GetMapping
@ResponseBody
public SessionInfo register(@RequestParam UserProfile userProfile) {
...
}
Spring picks up the converter automatically if you're using component scanning and annotate the converter class with @Component
.
如果您使用组件扫描并使用@Component
.
Learn more about Spring Converterand type conversions in Spring MVC.
了解有关Spring MVC 中的Spring Converter和类型转换的更多信息。