简体   繁体   中英

Generating json using spring-mvc

I tried to generate a json response earlier using spring-mvc (annotation) . After so may failure i find out some check point :

  1. I need to add <mvc:annotation-driven/> in my servelet mapper. although i don't know the reason.

  2. Then I need to add @ResponseBody annotation which should bound the return value as http response as the documentation says.

  3. And I also need add some jacson dependency.

Did i missed something? Now i have bunch of questions

  1. why we have to add that in my servelet xml and how this whole process is working?
  2. As json response is most commonly used when why spring need jackson dependency to generate json?

some days ago i was doing Struts2 generating json response there was much simple.

  1. Is there any way to do it more easily in spring-mvc .?

If you are using jacson you can do something like:

Your Model

public class Shop {     
    String name;    
    String staffName[]; 
}

Your Controller @Controller @RequestMapping("/shop/list") public class JSONController {

@RequestMapping(value="{name}", method = RequestMethod.GET)
public @ResponseBody Shop getShopInJSON(@PathVariable String name) {

    Shop shop = new Shop();
    shop.setName(name);
    shop.setStaffName(new String[]{"mkyong1", "mkyong2"});

    return shop;
}

}

mvc-dispatcher-servlet.xml

<context:component-scan base-package="com.example.mypackage" />
<mvc:annotation-driven />

Basically, you need check if: Your Jackson library is existed in the project classpath

The mvc:annotation-driven is enabled

Return method annotated with @ResponseBody

At first you should understand that <mvc:annotation-driven/> annotation used for many cases not only for generating json response in Spring. This annotation allow to use different annotations in Spring mvc classes like: @NumberFormat @DateFormat @Controller @Valid and of course @ResponseBody . To generate json response you just need @ResponseBody annotation in your controller or servlet and import libraries for processing JSON. Recently java has oun set of APIs for processing JSON as part of Java EE 7 JSR 353 actually it has clean Oracle tutorial . Also you can use third party libraries like Jackson . To process (parse, generate, transform, and query) JSON text it's necessarily to have one of this libs. You can learn about most popular third party libraries and their performance in this article

Here you can see simple example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM