序列化简介
个人理解,Json就是一种大家通用的数据传输格式。
提起Json,就不得不说下序列化和反序列化。
序列化
将代码中的实体数据转换成Json这种格式,便于数据传递与各类系统。
反序列化
将Json数据转换成代码中的实体数据。
代码
JsonTestModel jsonTestModel = new JsonTestModel();
jsonTestModel.setName("@JsonIgnoreProperties测试");
jsonTestModel.setTime(new Date());
testModel = jsonTestModel;
ObjectMapper mapper = new ObjectMapper();
//序列化
String json = mapper.writeValueAsString(testModel);
json = "{\"name\":\"@JsonIgnoreProperties测试\",\"time\":1575431118191}";
//反序列化
JsonTestModel readValue = mapper.readValue(json, JsonTestModel.class);
常用注解
@JsonIgnore(单字段序列化控制)
@JsonIgnoreProperties(类级序列化控制)
@JsonIgnoreType(该类作为别的类的属性时忽略序列化)
@JsonProperty(字段映射名称)
@JsonPropertyOrder(序列化时字段排序)
@JsonInclude(不序列化空字段)
@JsonBackReference和@JsonManagedReference(解决对象中存在双向引用导致的无限递归)
@JsonFormat(反序列化时,时间格式问题)
常用方法
json文件的读取
json文件
{
"name": "測試",
"time": "2019-12-04 00:00:00"
}
main方法
public class JsonUtils {
public static void main(String[] args) {
String json = "null";
try {
json = readJsonData("F:\\IdeaProject\\test\\demo\\src\\main\\resources\\json/readJson.json");
} catch (IOException e) {
e.printStackTrace();
}
JsonTestModel jsonTestModel= JSONObject.parseObject(json,JsonTestModel.class);
System.out.println(jsonTestModel.getName());
System.out.println(jsonTestModel.getTime());
}
public static String readJsonData(String path) throws IOException {
StringBuffer strbuffer = new StringBuffer();
File myFile = ResourceUtils.getFile(path);
FileInputStream fis = new FileInputStream(myFile);
InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
BufferedReader in = new BufferedReader(inputStreamReader);
String str;
while ((str = in.readLine()) != null) {
strbuffer.append(str); //new String(str,"UTF-8")
}
fis.close();
inputStreamReader.close();
in.close();
return strbuffer.toString();
}
}
spring boot test
public class JsonUtilsTest {
@Test
public void test(){
String json = "null";
try {
json = readJsonData("classpath:json/readJson.json");
} catch (IOException e) {
e.printStackTrace();
}
JsonTestModel jsonTestModel= JSONObject.parseObject(json,JsonTestModel.class);
System.out.println(jsonTestModel.getName());
System.out.println(jsonTestModel.getTime());
}
}
结果
測試
Wed Dec 04 00:00:00 CST 2019