使用 Jackson JSON 在 Spring MVC 中解析 JSON [英] Parsing JSON in Spring MVC using Jackson JSON

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

问题描述

好的,所以我已经研究了一段时间,不再继续了.我有一个 Spring MVC servlet,我需要从 JavaScript 前端 Web 应用程序接受 JSON.要解析 JSON,我需要使用 Jackson.我需要获取 JSON 中的值并按照它们在 JSON 中出现的顺序将它们存储到一个列表中.我已经尝试将 JsonFactory 与 JsonParser 和 JsonNode 对象一起使用,但完全可以让它工作.我也试过只打开一个 BufferedReader 并逐行遍历请求正文,但同样也无法完全理解.我在这里查看了几个相关的问题,但到目前为止没有一个对我有用.

Ok, so I've been looking at this for a little while now and am no further on. I've got a Spring MVC servlet that I need to accept JSON from a JavaScript front end web app. To parse the JSON I need to use Jackson. I need to take the values within the JSON and store them into a List in the order they appear in the JSON. I've tried using the JsonFactory with the JsonParser and JsonNode objects but can quite get it to work. I've also tried to just open a BufferedReader and iterate through the request body line by line but again can't quite get this either. I've looked at a couple of related questions on here, but none so far have worked for me.

任何知情人士能否在此指出我正确的方向,带有示例的网页会很棒!

Could anyone in the know point me in the right direction here please, a web page with an example would be great!

推荐答案

使用像 Jackson 这样的映射技术的全部意义在于您可以使用对象(您不必自己解析 JSON).

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

定义一个类似于您期望的 JSON 的 Java 类.

Define a Java class that resembles the JSON you will be expecting.

例如这个 JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}

可以映射到这个类:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

现在如果你有一个像这样的控制器方法:

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

然后你从上面传入 JSON,Jackson 会自动为你创建一个 Fizzle 对象,它会将返回的 Object 的 JSON 视图序列化为 mime 类型 application/json 的响应.

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

完整的工作示例 看我之前的回答.

这篇关于使用 Jackson JSON 在 Spring MVC 中解析 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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