Java中使用Jackson進行JSON解析和序列化
阿新 • • 發佈:2018-11-30
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);