目录
JSON是一种轻量级的数据格式,全称为JavaScript Object Notation
1.首先导入jar包
2.创建一个实体类
3.
对象-->JSON
//对象 ->json
@Test
public void test01() throws JsonProcessingException {
//1.1创建对象
Persion persion = new Persion("孙悟空", 1000, "男");
//2.创建jackson
ObjectMapper mapper = new ObjectMapper();
//3.调用方法完成转换
String s = mapper.writeValueAsString(persion);
System.out.println("s = " + s);//{"name":"孙悟空","age":1000,"gender":"男"}
}
List-->JSON
//list集合->json
@Test
public void test02() throws JsonProcessingException {
ArrayList<Persion> list = new ArrayList<>();
Collections.addAll(list,new Persion("孙悟空", 1000, "男"),
new Persion("沙悟净", 1000, "男"));
//2.创建jackson
ObjectMapper mapper = new ObjectMapper();
//3.调用方法完成转换
String s = mapper.writeValueAsString(list);
System.out.println("s = " + s);
}
Map-->JSON
//map -> JSON
@Test
public void test03() throws JsonProcessingException {
HashMap<String, Object> map = new HashMap<>();
map.put("name","孙悟空");
map.put("age",1222);
map.put("gender","男");
//2.创建jackson
ObjectMapper mapper = new ObjectMapper();
//3.调用方法完成转换
String s = mapper.writeValueAsString(map);
System.out.println("s = " + s);
}
JSON-->对象:
//JSON->对象
@Test
public void test01() throws IOException {
String s = "{\"name\":\"孙悟空\",\"age\":1000,\"gender\":\"男\"}";
ObjectMapper mapper = new ObjectMapper();
//第一个参数:json字符串,第二个参数:要转的类型
//为什么要.class,因为源码的第二个参数是class类型
Persion persion = mapper.readValue(s, Persion.class);
System.out.println(persion);
}
JSON-->List
//JSON->list集合
@Test
public void test02() throws IOException {
String s = "[{\"name\":\"孙悟空\",\"age\":1000,\"gender\":\"男\"}," +
"{\"name\":\"孙悟空\",\"age\":1000,\"gender\":\"男\"}]";
ObjectMapper mapper = new ObjectMapper();
ArrayList arrayList = mapper.readValue(s, ArrayList.class);
System.out.println("arrayList = " + arrayList);
}
JSON-->Map
@Test
public void test03() throws IOException {
String s = "{\"name\":\"孙悟空\",\"age\":1000,\"gender\":\"男\"}";
ObjectMapper mapper = new ObjectMapper();
HashMap map = mapper.readValue(s, HashMap.class);
System.out.println(map);
}
日期类型
如果在实体类中有日期类类型,转换json格式我们可以自定义格式
@Test
public void test01() throws JsonProcessingException {
Student student = new Student("tom", new Date());
ObjectMapper mapper = new ObjectMapper();
String string = mapper.writeValueAsString(student);
System.out.println("string = " + string);
//在日期类型变为毫秒值
//在日期字段加上注解:@JsonFormat(pattern = "yyyy-MM-dd")定义格式,
}