Jackson
作者:互联网
ObjectMapper
序列化与反序列化的工具类
此类中提供了readTree()
,readValue()
,writeValueAsString()
等方法用于转换。
ObjectMapper objectMapper = new ObjectMapper();
序列化
student student = new student();
String studentJson = objectMapper.writeValueAsString(student);
下面是一个studentJson
{
"name" : "zhangsan",
"age" : 18,
"code": [1,2],
"parents" : {
"father" : "baba",
"mother" : "mama"
}
}
一次性反序列化
//自定义dto
Student student = objectMapper.readValue(studentJson, Student.class);
//Map
Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
渐次反序列化
JsonNode student = objectMapper.readTree(studentJson);//将Json串以树状结构读入内存
JsonNode parents=node.get("parents");//得到parents这个节点下的信息
for(int i = 0; i < parents.size(); i++){
//遍历parents下的信息,size()获得parents下二级节点的个数
}
//获取student下二级节点的信息,形成迭代器
Iterator<JsonNode> elements = student.elements();
JsonNode
//JsonNode通过writeValueAsString方法可以产出Json
JsonNode student = objectMapper.readTree(studentJson);
String json = objectMapper.writeValueAsString(student);
//获取JsonNode field属性的信息,若field是ObjectNode,其value仍保持树状结构
JsonNode field = jsonNode.get("field");
//可以调用其中的asText()方法转换为String
//类似于cmd的cd命令 切换当前路径
JsonNode father = student.at("/parents/father");
//注意此时father为TextNode,value只有值
标签:JsonNode,Jackson,studentJson,parents,student,序列化,objectMapper 来源: https://www.cnblogs.com/yuking28/p/15772289.html