问题描述:
首先我遇到的第一个问题就是,在给前端传json数据。
我们前后端数据通信一般使用json格式的数据来传递, 那么后端如何给前端传值,以及我们有那么多的数据类型,都是怎么传递的呢?
public class JackSonTest {
//json传送一个实例对象
@Test
public void test1() throws Exception {
Person p = new Person();
p.setName("Jack");
p.setAge(22);
p.setGender("男");
//2.创建ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//3.转换
String s = mapper.writeValueAsString(p);
System.out.println(s);
//写入到指定文件中
//mapper.writeValue(new File("d://a.txt"),p);
//写入到指定流中
//mapper.writeValue(new FileOutputStream("d://a.txt"),p);
//mapper.writeValue(new FileWriter("d://a.txt"),p);
}
@Test
public void test2() throws JsonProcessingException {
Person p = new Person();
p.setName("Rose");
p.setAge(22);
p.setGender("女");
p.setBirthday(new Date());
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(p);
System.out.println(json);
}
//json传送一个list
@Test
public void test3() throws JsonProcessingException {
Person p = new Person();
p.setName("Haker");
p.setAge(33);
p.setGender("男");
p.setBirthday(new Date());
Person p1 = new Person();
p1.setName("Shelly");
p1.setAge(33);
p1.setGender("男");
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setName("Bale");
p2.setAge(33);
p2.setGender("男");
p2.setBirthday(new Date());
List<Person> list = new ArrayList<>();
list.add(p);
list.add(p1);
list.add(p2);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(list);
System.out.println(json);
}
//json传送一个map
@Test
public void test4() throws JsonProcessingException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Magie");
map.put("age", 22);
map.put("gender", "女");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
System.out.println(json);
}
//json字符串转换为一个实例对象
@Test
public void test5() throws JsonProcessingException {
String js = "{\"gender\":\"男\",\"name\":\"Tokky\",\"age\":22}";
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(js, Person.class);
System.out.println(person);
}
}
问题解决:
@Controller
public class FileController {
@ResponseBody
@RequestMapping("/test")
public String file() throws JsonProcessingException {
List<MyFile> list = new ArrayList<>(10);
list.add(new MyFile("01", new Date()));
list.add(new MyFile("02", new Date()));
list.add(new MyFile("03", new Date()));
list.add(new MyFile("04", new Date()));
list.add(new MyFile("05", new Date()));
list.add(new MyFile("06", new Date()));
list.add(new MyFile("07", new Date()));
list.add(new MyFile("08", new Date()));
list.add(new MyFile("09", new Date()));
list.add(new MyFile("10", new Date()));
list.add(new MyFile("11", new Date()));
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(list);
return json;
}
}
总结:
通过查阅资料学习;
解析,转换josn数据需要依赖第三方jar包:Jackson Databind、Jackson Core、Jackson Annotations
1.准备json数据,(对象、集合、字符串)
2.创建ObjectMapper对象
3.调用writeValueAsString方法
如果是解析json字符串调用readValue方法
|
|