ITeye博客

Java处理Json的简单方式

samjavaeye · 2017-01-04 10:56 · Java · 编程语言 · Markdown

先按Json字符串的格式定义好各级POJO对象,然后就可以简单的使用com.fasterxml.jackson.databind.ObjectMapper来进行Java 对象与Json字符串之间的互相转换。

 

先初始化

import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();

Java对象转字符串

Person person = new Person("张三", 38);
String jsonStr = objectMapper.writeValueAsString(person);

 字符串转Java对象

Person zhangSan = objectMapper.readValue("{\"name\":\"张三\",\"age\":38}", Person.class);

 字符串转List

List<Person> personList = objectMapper.readValue("[{\"name\":\"张三\",\"age\":38}]", objectMapper
	.getTypeFactory().constructParametricType(List.class, Person.class));

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。