The return value of the processor-json data processing
1. When will json be used?
ajax request
2. Convert between javaBean object and json, such as:阿里巴巴的fastjson
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
import com.alibaba.fastjson.JSON;
import org.junit.Test;
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);//{"id":1,"password":"1234","username":"jack"}
}
@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);//Person{id=1, username='jack', password='1234'}
}
}
3. Convert the return value to json @ResponseBody
Notes added to the method, SpringMVC can automatically method returns an object into json, 发送给页面
.
pom.xml
depends on jackson library
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
Demo02ReturnController
@RequestMapping("demo05.action")
//注解 @ResponseBody
//注解加在方法上,SpringMVC可以自动将方法的返回对象转为json,发送给页面
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
}
4. Parameter to json @RequestBody
Add the @RequestBody annotation in front of the formal parameter. This annotation can automatically parse the json data sent from the page 将json中的数据封装到形参对象
. After the analysis is completed, it will be automatically .
pom.xml
depends on jackson library
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
Demo02ReturnController
@RequestMapping("demo06.action")
//参数转json @RequestBody
//在形参的前边加上@RequestBody注解,该注解可以自动解析页面发送过来的json数据,解析完之后,自动的将json中的数据封装到形参对象
public ModelAndView test06(@RequestBody Person person){
//使用Postman传数据进行测试
System.out.println("object:"+person);
return null;
}
Use Postman to send json data to the server for
console printing