使用json进行序列化

package com.example.demo01;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;

/**
* @createTime 2020年11月27日 21:06:00
*/
public class TestJSONSerialization {

public static void main(String[] args) throws IOException {

Person person = new Person();
person.setAddress("hangzhou,china");
person.setAge(18);
person.setBirth(new Date());
person.setName("zhangsan");

//json对象序列化
String personJson = null;
ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
mapper.writeValue(gen, person);
gen.close();
personJson = sw.toString();

//json对象反序列化
Person zhangsan = (Person)mapper.readValue(personJson, Person.class);

System.out.println(personJson);
System.out.println(zhangsan.getName());
}
}
posted @ 2020-11-27 21:09  伤心的鸽子  阅读(386)  评论(0编辑  收藏  举报