Parsing JSON in Spring MVC using Jackson JSON

前端 未结 2 506
南方客
南方客 2020-11-28 21:44

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

2条回答
  •  鱼传尺愫
    2020-11-28 22:24

    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 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.

提交回复
热议问题