引入jar包(版本可以根据自己的需要修改)
compile group: 'com.fasterxml.jackson.core',name:'jackson-databind',version:'2.9.5'
创建类Student用于操作
package test;
import java.util.Date;
public class Student {
private String name;
private int age;
private Date birthDay;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//格式化日期属性
@JsonFormat(pattern = "yyyy-MM-dd ")
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
@Override
public String toString() {
return "Student[name="+this.name+",age="+this.age+",birthDay="+this.birthDay+"]";
}
}
使用(包含对象(集合等)转json,以及json转对象)
package com.telecom;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.telecom.agent.baseline.WindowsBaseLine;
import com.telecom.agent.util.Utils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
/**
* Created by HP on 2018/8/2.
*/
public class Test {
public static void main(String[] args) throws Exception{
ObjectMapper mapper = new ObjectMapper();
Student stu = new Student();
stu.setName("czz11");
stu.setAge(24);
stu.setBirthDay(new Date());
System.out.println("------------对象转成Json------------------");
String stuToJson = mapper.writeValueAsString(stu);
System.out.println(stuToJson);
System.out.println("------------json转成对象------------------");
String jsonToStu = "{\"name\":\"czz11\",\"age\":24,\"birthDay\":\"2019-08-06\"}";
Student stu1 = mapper.readValue(jsonToStu,Student.class);
System.out.println(stu1);
Student stu2 = new Student();
stu2.setName("czz22");
stu2.setAge(33);
stu2.setBirthDay(new Date());
System.out.println("------------集合转成Json------------------");
List<Student> list = new ArrayList<>();
list.add(stu);
list.add(stu2);
String json2 = mapper.writeValueAsString(list);
System.out.println(json2);
System.out.println("------------json转集合------------------");
//从JSON转换为Map对象的时候,由于Java的类型擦除,所以类型需要我们手动用new TypeReference<T>给出
List<Student> stis = mapper.readValue(json2,new TypeReference<ArrayList<Student>>(){});
for (Student ss:stis){
System.out.println(ss);
}
}
}
网友评论