Jackson庫(kù)中objectMapper的用法
Jackson庫(kù)中objectMapper用法
ObjectMapper類是Jackson庫(kù)的主要類。它提供一些功能將轉(zhuǎn)換成Java對(duì)象與SON結(jié)構(gòu)互相轉(zhuǎn)換,在項(xiàng)目中遇到過,故記錄一下。
在 pom.xml 加入依賴
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.3</version> </dependency>
創(chuàng)建一個(gè)實(shí)體類RiemannUser:
package com.test.objectMapper; import java.io.Serializable; import java.util.Date; import java.util.List; /** * @author riemann * @date 2019/05/27 22:48 */ public class RiemannUser implements Serializable { private static final long serialVersionUID = 1L; private int id; private String message; private Date sendDate; private String nodeName; private List<Integer> intList; public RiemannUser() { super(); } public RiemannUser(int id, String message, Date sendDate) { super(); this.id = id; this.message = message; this.sendDate = sendDate; } public static long getSerialVersionUID() { return serialVersionUID; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Date getSendDate() { return sendDate; } public void setSendDate(Date sendDate) { this.sendDate = sendDate; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public List<Integer> getIntList() { return intList; } public void setIntList(List<Integer> intList) { this.intList = intList; } @Override public String toString() { return "RiemannUser{" + "id=" + id + ", message='" + message + '\'' + ", sendDate=" + sendDate + ", nodeName='" + nodeName + '\'' + ", intList=" + intList + '}'; } }
先創(chuàng)建一個(gè)ObjectMapper,然后賦值一些屬性:
public static ObjectMapper mapper = new ObjectMapper(); static { // 轉(zhuǎn)換為格式化的json mapper.enable(SerializationFeature.INDENT_OUTPUT); // 如果json中有新增的字段并且是實(shí)體類類中不存在的,不報(bào)錯(cuò) mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); }
1、對(duì)象與json字符串、byte數(shù)組
@Test public void testObject() throws JsonGenerationException, JsonMappingException, IOException { RiemannUser riemann = new RiemannUser(1,"Hello World", new Date()); mapper.writeValue(new File("D:/test.txt"), riemann);//寫到文件中 //mapper.writeValue(System.out, riemann); //寫到控制臺(tái) String jsonStr = mapper.writeValueAsString(riemann); System.out.println("對(duì)象轉(zhuǎn)json字符串: " + jsonStr); byte[] byteArr = mapper.writeValueAsBytes(riemann); System.out.println("對(duì)象轉(zhuǎn)為byte數(shù)組:" + byteArr); RiemannUser riemannUser = mapper.readValue(jsonStr, RiemannUser.class); System.out.println("json字符串轉(zhuǎn)為對(duì)象:" + riemannUser); RiemannUser riemannUser2 = mapper.readValue(byteArr, RiemannUser.class); System.out.println("byte數(shù)組轉(zhuǎn)為對(duì)象:" + riemannUser2); }
運(yùn)行結(jié)果:
對(duì)象轉(zhuǎn)json字符串: {
"id" : 1,
"message" : "Hello World",
"sendDate" : 1558971056693,
"nodeName" : null,
"intList" : null
}
對(duì)象轉(zhuǎn)為byte數(shù)組:[B@31610302
json字符串轉(zhuǎn)為對(duì)象:RiemannUser{id=1, message='Hello World', sendDate=Mon May 27 23:30:56 CST 2019, nodeName='null', intList=null}
byte數(shù)組轉(zhuǎn)為對(duì)象:RiemannUser{id=1, message='Hello World', sendDate=Mon May 27 23:30:56 CST 2019, nodeName='null', intList=null}
2、list集合與json字符串
@Test public void testList() throws JsonGenerationException, JsonMappingException, IOException { List<RiemannUser> riemannList = new ArrayList<>(); riemannList.add(new RiemannUser(1,"a",new Date())); riemannList.add(new RiemannUser(2,"b",new Date())); riemannList.add(new RiemannUser(3,"c",new Date())); String jsonStr = mapper.writeValueAsString(riemannList); System.out.println("集合轉(zhuǎn)為字符串:" + jsonStr); List<RiemannUser> riemannLists = mapper.readValue(jsonStr, List.class); System.out.println("字符串轉(zhuǎn)集合:" + riemannLists); }
運(yùn)行結(jié)果:
集合轉(zhuǎn)為字符串:[ {
"id" : 1,
"message" : "a",
"sendDate" : 1558971833351,
"nodeName" : null,
"intList" : null
}, {
"id" : 2,
"message" : "b",
"sendDate" : 1558971833351,
"nodeName" : null,
"intList" : null
}, {
"id" : 3,
"message" : "c",
"sendDate" : 1558971833351,
"nodeName" : null,
"intList" : null
} ]
字符串轉(zhuǎn)集合:[{id=1, message=a, sendDate=1558971833351, nodeName=null, intList=null}, {id=2, message=b, sendDate=1558971833351, nodeName=null, intList=null}, {id=3, message=c, sendDate=1558971833351, nodeName=null, intList=null}]
3、map與json字符串
@Test public void testMap() { Map<String, Object> testMap = new HashMap<>(); testMap.put("name", "riemann"); testMap.put("age", 27); testMap.put("date", new Date()); testMap.put("user", new RiemannUser(1, "Hello World", new Date())); String jsonStr = null; try { jsonStr = mapper.writeValueAsString(testMap); System.out.println("Map轉(zhuǎn)為字符串:" + jsonStr); Map<String, Object> testMapDes = null; try { testMapDes = mapper.readValue(jsonStr, Map.class); System.out.println("字符串轉(zhuǎn)Map:" + testMapDes); } catch (IOException e) { e.printStackTrace(); } } catch (JsonProcessingException e) { e.printStackTrace(); } }
Map轉(zhuǎn)為字符串:{
"date" : 1558972169132,
"name" : "riemann",
"user" : {
"id" : 1,
"message" : "Hello World",
"sendDate" : 1558972169134,
"nodeName" : null,
"intList" : null
},
"age" : 27
}
字符串轉(zhuǎn)Map:{date=1558972169132, name=riemann, user={id=1, message=Hello World, sendDate=1558972169134, nodeName=null, intList=null}, age=27}
4、修改轉(zhuǎn)換時(shí)的日期格式:
@Test public void testOther() throws IOException { // 修改時(shí)間格式 mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); RiemannUser riemannUser = new RiemannUser(1,"Hello World",new Date()); riemannUser.setIntList(Arrays.asList(1,2,3)); String jsonStr = mapper.writeValueAsString(riemannUser); System.out.println("對(duì)象轉(zhuǎn)為字符串:" + jsonStr); }
運(yùn)行結(jié)果:
對(duì)象轉(zhuǎn)為字符串:{
"id" : 1,
"message" : "Hello World",
"sendDate" : "2019-05-27 23:53:55",
"nodeName" : null,
"intList" : [ 1, 2, 3 ]
}
objectMapper的一些坑
相信做過Java 開發(fā)對(duì)這個(gè)類應(yīng)該不陌生,沒錯(cuò),這個(gè)類是jackson提供的,主要是用來把對(duì)象轉(zhuǎn)換成為一個(gè)json字符串返回到前端,
現(xiàn)在大部分?jǐn)?shù)據(jù)交換都是以json來傳輸?shù)?所以這個(gè)很重要,那你到底又對(duì)這個(gè)類有著有多少了解呢,下面我說一下我遇到的一些坑
首先,先把我要說的幾個(gè)坑需要設(shè)置的屬性貼出來先
ObjectMapper objectMapper = new ObjectMapper(); //序列化的時(shí)候序列對(duì)象的所有屬性 objectMapper.setSerializationInclusion(Include.ALWAYS); //反序列化的時(shí)候如果多了其他屬性,不拋出異常 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //如果是空對(duì)象的時(shí)候,不拋異常 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //取消時(shí)間的轉(zhuǎn)化格式,默認(rèn)是時(shí)間戳,可以取消,同時(shí)需要設(shè)置要表現(xiàn)的時(shí)間格式 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
簡(jiǎn)單說一下這個(gè)類的基本用法,以下采用代碼塊加截圖的形式來說明和部分文字件數(shù)
package com.shiro.test; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class Main2 { public static void main(String[] args) throws Exception{ ObjectMapper objectMapper = new ObjectMapper(); //序列化的時(shí)候序列對(duì)象的所有屬性 objectMapper.setSerializationInclusion(Include.ALWAYS); //取消時(shí)間的轉(zhuǎn)化格式,默認(rèn)是時(shí)間戳,可以取消,同時(shí)需要設(shè)置要表現(xiàn)的時(shí)間格式 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); Person person = new Person(1, "zxc", new Date()); //這是最簡(jiǎn)單的一個(gè)例子,把一個(gè)對(duì)象轉(zhuǎn)換為json字符串 String personJson = objectMapper.writeValueAsString(person); System.out.println(personJson); //默認(rèn)為true,會(huì)顯示時(shí)間戳 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); personJson = objectMapper.writeValueAsString(person); System.out.println(personJson); } }
輸出的信息如下
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)的作用
package com.shiro.test; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class Main2 { public static void main(String[] args) throws Exception{ ObjectMapper objectMapper = new ObjectMapper(); //序列化的時(shí)候序列對(duì)象的所有屬性 objectMapper.setSerializationInclusion(Include.ALWAYS); //如果是空對(duì)象的時(shí)候,不拋異常,也就是對(duì)應(yīng)的屬性沒有g(shù)et方法 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); Person person = new Person(1, "zxc", new Date()); String personJson = objectMapper.writeValueAsString(person); System.out.println(personJson); //默認(rèn)是true,即會(huì)拋異常 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true); personJson = objectMapper.writeValueAsString(person); System.out.println(personJson); } }
對(duì)應(yīng)的person類此時(shí)為
package com.shiro.test; import java.util.Date; public class Person { private Integer id; private String name; private Date birthDate; // public Integer getId() { // return id; // } // public void setId(Integer id) { // this.id = id; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public Date getBirthDate() { // return birthDate; // } // public void setBirthDate(Date birthDate) { // this.birthDate = birthDate; // } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", birthDate=" + birthDate + "]"; } public Person(Integer id, String name, Date birthDate) { super(); this.id = id; this.name = name; this.birthDate = birthDate; } public Person() { // TODO Auto-generated constructor stub } }
結(jié)果如下
package com.shiro.test; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class Main2 { public static void main(String[] args) throws Exception{ ObjectMapper objectMapper = new ObjectMapper(); //序列化的時(shí)候序列對(duì)象的所有屬性 objectMapper.setSerializationInclusion(Include.ALWAYS); //反序列化的時(shí)候如果多了其他屬性,不拋出異常 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Person person = new Person(1, "zxc", new Date()); // String personJson = objectMapper.writeValueAsString(person); // System.out.println(personJson); //注意,age屬性是不存在在person對(duì)象中的 String personStr = "{\"id\":1,\"name\":\"zxc\",\"age\":\"zxc\"}"; Person person = objectMapper.readValue(personStr, Person.class); System.out.println(person); //默認(rèn)為true objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); person = objectMapper.readValue(personStr, Person.class); System.out.println(person); } }
執(zhí)行后的結(jié)果如下
這些便是這幾個(gè)屬性的作用所以,由于第一個(gè)比較簡(jiǎn)單我就這樣說一下吧
Include.ALWAYS 是序列化對(duì)像所有屬性
Include.NON_NULL 只有不為null的字段才被序列化
Include.NON_EMPTY 如果為null或者 空字符串和空集合都不會(huì)被序列化
然后再說一下如何把一個(gè)對(duì)象集合轉(zhuǎn)換為一個(gè) Java里面的數(shù)組
package com.shiro.test; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; public class Main2 { public static void main(String[] args) throws Exception{ ObjectMapper objectMapper = new ObjectMapper(); //序列化的時(shí)候序列對(duì)象的所有屬性 objectMapper.setSerializationInclusion(Include.NON_DEFAULT); Person person1 = new Person(1, "zxc", new Date()); Person person2 = new Person(2, "ldh", new Date()); List<Person> persons = new ArrayList<>(); persons.add(person1); persons.add(person2); //先轉(zhuǎn)換為json字符串 String personStr = objectMapper.writeValueAsString(persons); //反序列化為L(zhǎng)ist<user> 集合,1需要通過 TypeReference 來具體傳遞值 List<Person> persons2 = objectMapper.readValue(personStr, new TypeReference<List<Person>>() {}); for(Person person : persons2) { System.out.println(person); } //2,通過 JavaType 來進(jìn)行處理返回 JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Person.class); List<Person> persons3 = objectMapper.readValue(personStr, javaType); for(Person person : persons3) { System.out.println(person); } } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java動(dòng)態(tài)添加外部jar包到classpath的實(shí)例詳解
這篇文章主要介紹了java動(dòng)態(tài)添加外部jar包到classpath的實(shí)例詳解的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-09-09Java和Python現(xiàn)在都挺火,我應(yīng)該怎么選?
這篇文章主要介紹了Java和Python現(xiàn)在都挺火,我應(yīng)該怎么選?本文通過全面分析給大家做個(gè)參考,需要的朋友可以參考下2020-07-07解決Mybatis出現(xiàn)報(bào)錯(cuò)Error querying database.Cause: j
這篇文章主要介紹了解決Mybatis出現(xiàn)報(bào)錯(cuò)Error querying database.Cause: java.lang.IndexOutOfBoundsException: Index 9 out of,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05詳解RabbitMQ中死信隊(duì)列和延遲隊(duì)列的使用詳解
這篇文章主要為大家介紹了RabbitMQ中死信隊(duì)列和延遲隊(duì)列的原理與使用,這也是Java后端面試中常見的問題,感興趣的小伙伴可以了解一下2022-05-05解決@Autowired注入空指針問題(利用Bean的生命周期)
這篇文章主要介紹了解決@Autowired注入空指針問題(利用Bean的生命周期),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02Java?離線中文語(yǔ)音文字識(shí)別功能的實(shí)現(xiàn)代碼
這篇文章主要介紹了Java?離線中文語(yǔ)音文字識(shí)別,本次使用springboot?+maven實(shí)現(xiàn),官方demo為springboot+gradle,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07