JAVA framework json data interaction

1. Import dependencies:

 1     <dependency>
 2       <groupId>com.fasterxml.jackson.core</groupId>
 3       <artifactId>jackson-annotations</artifactId>
 4       <version>2.5.0</version>
 5     </dependency>
 6     <dependency>
 7       <groupId>com.fasterxml.jackson.core</groupId>
 8       <artifactId>jackson-core</artifactId>
 9       <version>2.5.4</version>
10     </dependency>
11       <dependency>
12           <groupId>com.fasterxml.jackson.core</groupId>
13           <artifactId>jackson-databind</artifactId>
14           <version>2.5.4</version>
15       </dependency>

 

Second, import jquery.

3. js code:

 1     function senJson() {
 2         $.ajax({
 3             type:"post",
 4             url:"${pageContext.request.contextPath }/goods/senJson.action",
 5             contentType:"application/json;charset=utf-8",
 6             data:'{"goodsname":"测试商品","money":99}',
 7             success:function(data){
 8                 alert(data);
 9             }
10         });
11 
12     }

 

Fourth, the controller code:

Use @RequestBody  to receive json data and convert it into a corresponding object.

Use @ResponseBody to convert the object to the corresponding json data.

Code:

1     @ResponseBody
2     @RequestMapping("/senJson")
3     public goods  senJson(@RequestBody goods goods){
4         System.out.println(goods.getGoodsname()+" "+goods.getMoney());
5         return goods;
6     }

 

Note that one is RequestBody and   the other is ResponseBody is different.

Also the return value is an object not a string!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325179276&siteId=291194637