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

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

问题描述

好的,所以我现在已经看了一会儿这一点,我再也没有了。我有一个Spring MVC servlet,我需要从JavaScript前端Web应用程序接受JSON。要解析JSON,我需要使用Jackson。我需要获取JSON中的值,并按照它们在JSON中出现的顺序将它们存储到List中。我已经尝试将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!

推荐答案

使用像杰克逊这样的地图技术的全部意义在于你可以使用对象(您不必自己解析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,杰克逊会自动创建一个Fizzle对象为你,它将序列化返回的对象的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.

有关完整的工作示例,请看到我之前的答案

For a full working example see this previous answer of mine.

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

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