I tried to generate a json response earlier using spring-mvc (annotation)
. After so may failure i find out some check point :
I need to add <mvc:annotation-driven/>
in my servelet mapper. although i don't know the reason.
Then I need to add @ResponseBody
annotation which should bound the return value as http response as the documentation says.
Did i missed something? Now i have bunch of questions
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.
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.