标签:cto eval mave tor exception mat .data ide imp
Java中使用Jackson进行JSON解析和序列化1.添加依赖,在Maven的pom.xml文件中添加以下依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
2.封装JSON解析和序列化工具类
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
// JSON/对象转换类
public class JsonUtils {
// 定义jackson对象
private static ObjectMapper MAPPER=new ObjectMapper();
// 将对象转换成json字符串
public static String objectToJson(Object obj){
try {
String str=MAPPER.writeValueAsString(obj);
return str;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
// 将json数据转换成pojo对象
public static <T> T jsonToObject(String json,Class<T> beanType){
try {
T t=MAPPER.readValue(json, beanType);
return t;
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 将json数据转换成pojo对象list
public static <T> List<T> jsonToList(String json,Class<T> beanType){
JavaType javaType=MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try{
List<T> list=MAPPER.readValue(json, javaType);
return list;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
3.使用
(1)自定义对象:User
import java.util.Date;
public class User {
private String name;
private Integer age;
private Date birthday;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", birthday=" + birthday + ", email=" + email + "]";
}
}
(2)工具类的使用
I.序列化对象
List<User> users=new ArrayList<User>();
for(int i=0;i<20;i++){
User user=new User();
user.setName("Apple"+i);
user.setAge(20+i);
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateformat.parse("1991-10-01"));
user.setEmail("12345678"+i+"@qq.com");
// 序列化单个对象
// String json=JsonUtils.objectToJson(user);
users.add(user);
// 序列化对象列表
String json=JsonUtils.objectToJson(users);
System.out.println(json);
}
II.反序列化对象
// 反序列化单个对象
User u=JsonUtils.jsonToObject(record.value(), User.class);
System.out.println(u.toString());
// 序列化对象列表
List<User> list=JsonUtils.jsonToList(record.value(), User.class);
System.out.println(list);
标签:cto eval mave tor exception mat .data ide imp
原文地址:http://blog.51cto.com/59465168/2324332