0
点赞
收藏
分享

微信扫一扫

Day25SSM之SpringMVC 返回值类型为Object 之json处理


处理器的返回值-json数据处理

  • (1)什么时候使用到json?
    ajax请求
  • (2)javaBean对像与json互转 如​​阿里巴巴的fastjson​
  • (3)返回值转json​​@ResponseBody​​ 注解加在方法上,SpringMVC可以自动将方法的返回对象转为json,发送给页面
  • (4)参数转json​​@RequestBody​​ 在形参的前边加上@RequestBody注解,该注解可以自动解析页面发送过来的json数据,解析完之后,自动的将json中的数据封装到形参对象

pom.xml

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

TestPersnoToJson

public class TestPersnoToJson {
@Test
public void test01(){
Person p = new Person(1,"jack","1234");
String json = JSON.toJSONString(p);//调用静态方法toJSONString,参数传入对象 ,将对象转成json
System.out.println(json);
}
@Test
public void test02(){
String json = "{\"id\":1,\"password\":\"1234\",\"username\":\"jack\"}";
Person p = JSON.parseObject(json,Person.class);//json转javaBean,参1,json 参2 类
System.out.println(p);
}
}

pom.xml

依赖 jackson库

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>

Demo02ReturnController

@RequestMapping(path = "demo05.action",method = {RequestMethod.POST,RequestMethod.GET})//回显页面
public @ResponseBody Object test05(){//

Person p1 = new Person(1,"jack","1234");
Person p2 = new Person(2,"rose","1234");
List<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
return list; //springmvc将 list使用ObjectMapper转成json
}
@RequestMapping(path = "demo06.action",method = {RequestMethod.POST,RequestMethod.GET})//回显页面
public ModelAndView test06(@RequestBody Person person){//
System.out.println("object:"+person);
return null;
}

PostMan

Day25SSM之SpringMVC 返回值类型为Object 之json处理_ajax


举报

相关推荐

0 条评论