本文主要是介绍初步探索jackson对json格式处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
简介
Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。
jackson所需要的jar包可从此处下载
代码实战
javaimport com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;public class test {public static void main(String[] args) {ObjectMapper objectMapper = new ObjectMapper();// 设置日期格式化objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));// 设置null不序列化objectMapper.setSerializationInclusion(Include.NON_NULL);try {//用户对象转为Json串Person person1 = new Person("redgo", 20);String json_person1 = objectMapper.writeValueAsString(person1); //{"name":"redgo","age":20}Person person2 = new Person("bluego", 22);String json_person2 = objectMapper.writeValueAsString(person2);//List对象转为Json串List<Person> list = new ArrayList<Person>();list.add(person1);list.add(person2);String json_list = objectMapper.writeValueAsString(list); //[{"name":"redgo","age":20},{"name":"bluego","age":22}]//JSON串转为用户对象person1 =objectMapper.readValue(json_person1, Person.class);//JSON串转为List对象JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, Person.class);list = (List<Person>)objectMapper.readValue(json_list, javaType);//用户组对象(包含List集合)转为Json串PersonGroup personGroup = new PersonGroup("亲戚", list);String json_personGroup = objectMapper.writeValueAsString(personGroup);//{"name":"亲戚","persons":[{"age":20,"name":"redgo"},{"age":22,"name":"bluego"}]}//JSON串转为用户组对象(包含List集合)personGroup =objectMapper.readValue(json_personGroup, PersonGroup.class);} catch (Exception e) {e.printStackTrace();}}}
Person类
javapublic class Person {private String name;private int age;public Person(){}public Person(String name, int age){this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}
}
PersonGroup类
javapublic class PersonGroup {private String name;private List<Person> persons = new ArrayList<Person>();public PersonGroup(){};public PersonGroup(String name, List<Person> persons){this.name = name;this.persons = persons;};public String getName() {return name;}public void setName(String name) {this.name = name;}public List<Person> getPersons() {return persons;}public void setPersons(List<Person> persons) {this.persons = persons;}@Overridepublic String toString() {return "PersonGroup [name=" + name + ", persons=" + persons + "]";}
}
这篇关于初步探索jackson对json格式处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!