Spring MVC,反序列化单个JSON? [英] Spring MVC, deserialize single JSON?
问题描述
如何轻松分离在同一请求中发送的JSON值?
How can I easily separate JSON values that are sent in the same request?
鉴于我将JSON发布到我的服务器:
Given that I POST a JSON to my server:
{"first":"A","second":"B"}
如果我在Controller中实现以下方法:
If I implement the following method in the Controller:
@RequestMapping(value = "/path", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void handleRequest(@RequestBody String input) {
// ...
}
然后输入
参数将构成一个整个字符串JSON对象, {first:A,second:B}
。我真正想要的是两个单独的字符串(或一个适合特定请求的字符串和一个int),只有两个值(客户端可能发送的其他键/值对应该被忽略)。
then the input
parameter will constitute a String with the entire JSON object, {"first":"A","second":"B"}
. What I really want is two separate Strings (or a String and an int whichever is suitable for the particular request) with just the two values (other key / value pairs that the client may send should be ignored).
如果字符串是作为请求参数而不是JSON请求体发送的,那么这很简单:
If the strings were sent as request parameters instead of JSON request body it would be simple:
@RequestMapping(value = "/path", method = RequestMethod.POST)
public void handleRequest(@RequestParam("first") String first,
@RequestParam("second") String second) {
// ...
}
I知道我可以创建一个简单的bean类,它可以与 @RequestBody
注释一起使用,它将包含 A
和 B
使用时,但它似乎是绕道而行,因为它们在网络应用程序中会有不同的用途。
I know that I can create a simple bean class that can be used in conjunction with the @RequestBody
annotation that will contain both A
and B
when used, but it seems like a detour, since they will have different purposes inside the web app.
依赖关系:
org.springframework:spring-web:3.1.0.RELEASE
org.codehaus.jackson:jackson-mapper-asl:1.9.3
Dependencies: org.springframework : spring-web : 3.1.0.RELEASE org.codehaus.jackson : jackson-mapper-asl : 1.9.3
推荐答案
POJO
POJO
public class Input {
private String first;
private String second;
//getters/setters
}
...然后:
public void handleRequest(@RequestBody Input input)
在这种情况下,您需要在CLASSPATH上提供 Jackson 。
In this case you need Jackson to be available on the CLASSPATH.
public void handleRequest(@RequestBody Map<String, String> input)
这篇关于Spring MVC,反序列化单个JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!