目录
- 如何将一个Json序列化对象封装成为一个Pojo是实体类对象
- 如何进行序列化与反序列化
- 如何将数据进行绑定
- 如何进行泛型数据绑定
- 如何使用Jackson树模型(将复杂Json手动映射到类型)
- 使用Jackson进行流式处理
如何将一个Json序列化对象封装成为一个Pojo是实体类对象
public static void main(String[] args) {
//创建ObjectMapper对象,这是一个可重复使用的对象
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
//map to json student
try {
//反序列化得到JSON对象,
// 从JSON对象使用readValue方法来获取,通过JSON字符串对象类型作为参数JSON字符串(json字符串,字符串类型)
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student.toString());
//设置JSON的格式[缩进、单\双引号....]
mapper.enable(SerializationFeature.INDENT_OUTPUT);
//使用writeValueAsString()方法来获取对象的JSON字符串表示。
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
如何进行序列化与反序列化
public static void main(String[] args) {
JacksonSer jacksonSer = new JacksonSer();
try {
Student student = new Student();
student.setAge(22);
student.setName("RenZetong");
//将Pojo对象序列化为Json
jacksonSer.writeJSON(student);
//将Json反序列化为Pojo对象
Student student1 = jacksonSer.readJSON();
System.out.println(student1);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 序列化
*
* @param student
* @throws Exception
*/
private void writeJSON(Student student) throws Exception {
ObjectMapper mapper = new ObjectMapper();
//使用writeValue来将Json文件写入(Json文件,映射类)
mapper.writeValue(new File("./data/student.json"), student);
}
/**
* 反序列化
*
* @return
* @throws Exception
*/
private Student readJSON() throws Exception {
ObjectMapper mapper = new ObjectMapper();
//从JSON对象使用readValue方法来获取,通过JSON字符串对象类型作为参数JSON字符串(json字符串,字符串类型)
Student student = mapper.readValue(new File("./data/student.json"), Student.class);
return student;
}
如何将数据进行绑定
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> studentMap = new HashMap<>();
int[] marks = {1, 2, 3};
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
//Java Object 也就是实体类对象
studentMap.put("student", student);
//Java String 也就是键值对
studentMap.put("name", "Mahesh Kumar");
//Java Boolean
studentMap.put("verified", Boolean.FALSE);
//Array Type 数组类型
studentMap.put("marks", marks);
//将map数据序列化为Json
//mapper.writeValue(new File("./data/students.json"), studentMap);
//将复杂型Json通过readValue解析到Map集合中(Json文件,映射类型) 反序列化
studentMap = mapper.readValue(new File("./data/students.json"), Map.class);
//反序列化集合中的Json数据
System.out.println(studentMap.get("student"));
System.out.println(studentMap.get("name"));
System.out.println(studentMap.get("verified"));
System.out.println(studentMap.get("marks"));
//反序列化数组对象
List<Integer> list = (List<Integer>) studentMap.get("marks");
for (Integer integer : list) {
System.out.println(integer);
}
}
如何进行泛型数据绑定
public String method() throws IOException {
ObjectMapper mapper = new ObjectMapper();
User user = new User();
user.setId(1);
Pager<User> pager = new Pager<User>();
List<User> users = new ArrayList<User>();
users.add(user);
pager.setDatas(users);
String json = mapper.writeValueAsString(pager);
// 方式1
Pager<User> userPager1 = mapper.readValue(json, new TypeReference<Pager<User>>() {
});
// 方式2
Type[] types = new Type[1];
types[0] = User.class;
final ParameterizedTypeImpl type = ParameterizedTypeImpl.make(Pager.class, types, Pager.class.getDeclaringClass());
TypeReference typeReference = new TypeReference<Pager>() {
@Override
public Type getType() {
return type;
}
};
Pager<User> userPager2 = mapper.readValue(json, typeReference);
// 方式3
JavaType javaType = mapper.getTypeFactory().constructParametrizedType(Pager.class, Pager.class, User.class);
Pager<User> userPager3 = mapper.readValue(json, javaType);
// 方式4
JavaType javaType1 = mapper.getTypeFactory().constructParametricType(Pager.class, User.class);
Pager<User> userPager4 = mapper.readValue(json, javaType1);
// 方式5,新建另一个指定具体泛型T的参数的类
PagerAppoint userPager5 = mapper.readValue(json, PagerAppoint.class);
// 数组泛型的序列化和反序列化
String json1 = mapper.writeValueAsString(users);
JavaType javaType2 = mapper.getTypeFactory().constructParametricType(List.class, User.class);
List<User> users1 = mapper.readValue(json1, javaType2);
// HashMap
Map<String, User> map = new HashMap<String, User>(16);
map.put("test", user);
String json2 = mapper.writeValueAsString(map);
// 1
Map<String, User> users2 = mapper.readValue(json2, new TypeReference<Map<String, User>>() {
});
// 2
JavaType javaType3 = mapper.getTypeFactory().constructParametricType(HashMap.class, String.class, User.class);
Map<String, User> users3 = mapper.readValue(json2, javaType3);
return "hello world";
}
}
如何使用Jackson树模型(将复杂Json手动映射到类型)
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
//使用readTree来读取json数据
JsonNode rootNode = mapper.readTree(jsonString);
//使用path获取节点
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: " + nameNode.textValue());
JsonNode ageNode = rootNode.path("age");
System.out.println("Age: " + ageNode.intValue());
JsonNode verifiedNode = rootNode.path("verified");
System.out.println("Verified: " + verifiedNode.booleanValue());
JsonNode marksNode = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode.elements();
System.out.println("Marks:[");
for (JsonNode node : marksNode) {
System.out.println(node.intValue());
}
System.out.println("]");
}
读取json文件进行树遍历
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode;
//读取Json文件到JsonNode;
rootNode = mapper.readTree(new File("./data/students.json"));
//使用树模型来读取Json文件并映射到Pojo对象
UserInfo userInfo = mapper.treeToValue(rootNode, UserInfo.class);
System.out.println("Name: " + userInfo.getName());
}
使用Jackson进行流式处理
JacksonParse类用于读取Json,JacksonGenerator用于编写Json
public static void main(String[] args) throws Exception {
//writeJSON();
readJSON();
}
//使用JsonGenerator写入JSON
public static JsonGenerator writeJSON() throws Exception {
JsonFactory jsonFactory = new JsonFactory();
//创建json输出路径以及字符编码
JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File("./data/stu.json"), JsonEncoding.UTF8);
//{
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "RenZetong");
jsonGenerator.writeNumberField("age", 22);
jsonGenerator.writeBooleanField("verified", false);
//marks:[
jsonGenerator.writeFieldName("marks");
jsonGenerator.writeStartArray();
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
jsonGenerator.writeEndArray();
//]
jsonGenerator.writeEndObject();
jsonGenerator.close();
//}
return jsonGenerator;
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
}
//使用JsonParser解析JSON字符串
public static void readJSON() throws Exception {
JsonFactory jsonFactory = new JsonFactory();
JsonParser jsonParser = jsonFactory.createParser(new File("./data/stu.json"));
//如果没有迭代到Json对象结束节点则一直循环
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
//获取当前节点名称
String fieldName = jsonParser.getCurrentName();
if ("name".equals(fieldName)) {
//如果没有剩余标记则停止迭代
jsonParser.nextToken();
//获取当前节点值
System.out.println(jsonParser.getText());
}
if ("age".equals(fieldName)) {
jsonParser.nextToken();
System.out.println(jsonParser.getNumberValue());
}
if ("verified".equals(fieldName)) {
jsonParser.nextToken();
System.out.println(jsonParser.getBooleanValue());
}
if ("marks".equals(fieldName)) {
jsonParser.nextToken();
//如果没有迭代到Json数组对象结束节点则一直循环
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
System.out.println(jsonParser.getNumberValue());
}
}
}
}
标签:基本,mapper,教程,Jackson,System,json,student,println,new
From: https://www.cnblogs.com/MineLSG/p/17998504