使用Jackson JSON解析Spring MVC中的JSON(Parsing JSON in Spring MVC using Jackson JSON)

编程入门 行业动态 更新时间:2024-10-20 11:36:16
使用Jackson JSON解析Spring MVC中的JSON(Parsing JSON in Spring MVC using Jackson 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这样的映射技术的关键是你可以使用Objects(你不必自己解析JSON)。

定义一个Java类,类似于您期待的JSON。

例如这个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 }

现在,如果您有像这样的Controller方法:

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

并且您从上方传入JSON,Jackson会自动为您创建一个Fizzle对象,并且它会将返回的Object的JSON视图序列化为MIME类型application/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).

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

e.g. this JSON:

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

could be mapped to this class:

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); }

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.

更多推荐

本文发布于:2023-07-06 07:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047367.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSON   Jackson   Spring   Parsing   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!