1.导入相应jackson的jar包
2.需要转化解析的类Person.java
public class Person{
private String name;
private int 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;
}
}
3.Java对象转Json
public class JacksonTest {
public static void main(String[] args) throws IOException{
ObjectMapper objectMapper = new ObjectMapper();
Person person1 = new Person();
person1.setName("sbw");
person1.setAge(24);
Person person2 = new Person();
person2.setName("gy");
person2.setAge(25);
/**
* 普通对象转Json
*/
String json = objectMapper.writeValueAsString(person1);//转为字符串
System.out.println(json);
/**
* List转Json
*/
List<Person> list = new ArrayList<Person>();
list.add(person1);
list.add(person2);
String listJson = objectMapper.writeValueAsString(list);
System.out.println(listJson);
/**
* Map转Json
*/
Map<String, Person> map = new HashMap<String, Person>();
map.put("person1", person1);
map.put("person2", person2);
objectMapper.writeValue(System.out, map);//System.out已可以转为其他流
}
}
执行结果:
4.Json转Java对象
public class JacksonTest {
public static void main(String[] args) throws IOException{
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"name\":\"sbw\",\"age\":24}";//普通
String listJson = "[{\"name\":\"sbw\",\"age\":24},{\"name\":\"gy\",\"age\":25}]";//List
String mapJson = "{\"person1\":{\"name\":\"sbw\",\"age\":24},\"person2\":{\"name\":\"gy\",\"age\":25}}";//Map
/**
* Json转Java对象
*/
Person person = objectMapper.readValue(json, Person.class);
System.out.println(person.getName() + " " + person.getAge());
System.out.println();
/**
* Json转List
*/
@SuppressWarnings("unchecked")
List<LinkedHashMap<String, Object>> list = objectMapper.readValue(listJson, List.class);
for(LinkedHashMap<String, Object> ll : list){
for(Map.Entry<String, Object> mm: ll.entrySet()){
System.out.println(mm.getKey() + " " + mm.getValue());
}
}
System.out.println();
/**
*Json转数组
*/
Person[] per = objectMapper.readValue(listJson, Person[].class);
for(Person p : per){
System.out.println(p.getName() + " " + p.getAge());
}
System.out.println();
/**
* Json转Map
*/
@SuppressWarnings("unchecked")
Map<String, Person> map = objectMapper.readValue(mapJson, Map.class);
for(Map.Entry<String, Person> m : map.entrySet()){
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
执行结果: