解決ObjectMapper.convertValue() 遇到的一些問題
源代碼:
public <T> T convertValue(Object fromValue, TypeReference<?> toValueTypeRef) throws IllegalArgumentException { return (T) _convert(fromValue, _typeFactory.constructType(toValueTypeRef)); }
該方法用于用jackson將bean轉(zhuǎn)換為map
例子:
List<SObject> sObjects = new ObjectMapper().convertValue(map.get("list"), new TypeReference<List<SObject>>() { });
微服務(wù)中從其他服務(wù)獲取過來的對(duì)象,如果從Object強(qiáng)轉(zhuǎn)為自定義的類型會(huì)報(bào)錯(cuò),利用ObjectMapper轉(zhuǎn)換。
ObjectMapper mapper = new ObjectMapper(); DefaultResponse defaultResponse = proxy.getData(); List<Resource> resources = (<Resource>) defaultResponse.getData(); //這里的場(chǎng)景是:data是一個(gè)Object類型的,但是它其實(shí)是一個(gè)List<Resouce>,想把List中的每個(gè)對(duì)象分別轉(zhuǎn)成可用的對(duì)象 for (int i = 0; i < serviceDateResources.size(); i++) { Resource resource = mapper.convertValue(resources.get(i), Resource.class); //經(jīng)過這步處理,resource就是可用的類型了,如果不轉(zhuǎn)化會(huì)報(bào)錯(cuò) }
在轉(zhuǎn)換過程中有些屬性被設(shè)置為空,這樣就不需要轉(zhuǎn)化
處理方法:
在需要轉(zhuǎn)化的實(shí)體類商添加如下注解
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.Include.ALWAYS) 默認(rèn) @JsonInclude(Include.NON_DEFAULT) 屬性為默認(rèn)值不序列化 @JsonInclude(Include.NON_EMPTY) 屬性為 空(“”) 或者為 NULL 都不序列化 @JsonInclude(Include.NON_NULL) 屬性為NULL 不序列化
jackson objectMapper json字符串、對(duì)象bean、map、數(shù)組list互相轉(zhuǎn)換常用的方法列舉:
ObjectMapper mapper = new ObjectMapper();
1.對(duì)象轉(zhuǎn)json字符串
User user=new User(); String userJson=mapper.writeValueAsString(user);
2.Map轉(zhuǎn)json字符串
Map map=new HashMap(); String json=mapper.writeValueAsString(map);
3.數(shù)組list轉(zhuǎn)json字符串
Student[] stuArr = {student1, student3}; String jsonfromArr = mapper.writeValueAsString(stuArr);
4.json字符串轉(zhuǎn)對(duì)象
String expected = "{\"name\":\"Test\"}"; User user = mapper.readValue(expected, User.class);
5.json字符串轉(zhuǎn)Map
String expected = "{\"name\":\"Test\"}"; Map userMap = mapper.readValue(expected, Map.class);
6.json字符串轉(zhuǎn)對(duì)象數(shù)組List
String expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]"; CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class); List<User> userList = mapper.readValue(expected, listType);
7.json字符串轉(zhuǎn)Map數(shù)組List<Map<String,Object>>
String expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]"; CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Map.class); List<Map<String,Object>> userMapList = mapper.readValue(expected, listType);
8.jackson默認(rèn)將對(duì)象轉(zhuǎn)換為L(zhǎng)inkedHashMap:
String expected = "[{\"name\":\"Ryan\"},{\"name\":\"Test\"},{\"name\":\"Leslie\"}]"; ArrayList arrayList = mapper.readValue(expected, ArrayList.class);
9.json字符串與list或map互轉(zhuǎn)的方法
ObjectMapper objectMapper = new ObjectMapper(); //遇到date按照這種格式轉(zhuǎn)換 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); objectMapper.setDateFormat(fmt); String preference = "{name:'侯勇'}"; //json字符串轉(zhuǎn)map Map<String, String> preferenceMap = new HashMap<String, String>(); preferenceMap = objectMapper.readValue(preference, preferenceMap.getClass()); //map轉(zhuǎn)json字符串 String result=objectMapper.writeValueAsString(preferenceMap);
10.bean轉(zhuǎn)換為map
List<Map<String,String>> returnList=new ArrayList<Map<String,String>>(); List<Menu> menuList=menuDAOImpl.findByParentId(parentId); ObjectMapper mapper = new ObjectMapper(); //用jackson將bean轉(zhuǎn)換為map returnList=mapper.convertValue(menuList,new TypeReference<List<Map<String, String>>>(){});
objectMapper.convertValue() 報(bào)錯(cuò)
報(bào)錯(cuò)信息如下:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDateTime (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: net.too1.tplus.user.user.entity.User[“createTime”])
根據(jù)以上報(bào)錯(cuò)得知, 是java.time.LocalDateTime類型的原因. ObjectMapper 不能對(duì)LocalDateTime 序列化. 加上以下注解即可解決
@JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonSerialize(using = LocalDateTimeSerializer.class)
@ApiModelProperty(value = "創(chuàng)建時(shí)間") @JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonSerialize(using = LocalDateTimeSerializer.class) private LocalDateTime createTime;
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
實(shí)戰(zhàn)干貨之基于SpringBoot的RabbitMQ多種模式隊(duì)列
RabbitMQ 是一個(gè)由Erlang語言開發(fā)的AMQP的開源實(shí)現(xiàn),支持多種客戶端。用于在分布式系統(tǒng)中存儲(chǔ)轉(zhuǎn)發(fā)消息,在易用性、擴(kuò)展性、高可用性等方面表現(xiàn)不俗,下文將帶你深入了解 RabbitMQ 多種模式隊(duì)列2021-09-09SpringBoot2.7?WebSecurityConfigurerAdapter類過期配置
這篇文章主要為大家介紹了SpringBoot2.7中WebSecurityConfigurerAdapter類過期應(yīng)該如何配置,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06springboot啟動(dòng)feign項(xiàng)目報(bào)錯(cuò):Service id not legal hostnam的解決
這篇文章主要介紹了springboot啟動(dòng)feign項(xiàng)目報(bào)錯(cuò):Service id not legal hostnam的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08Springboot的maven間接依賴的實(shí)現(xiàn)
這篇文章主要介紹了Springboot的maven間接依賴的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05SpringBoot獲取當(dāng)前運(yùn)行環(huán)境三種方式小結(jié)
在使用SpringBoot過程中,我們只需要引入相關(guān)依賴,然后在main方法中調(diào)用SpringBootApplication.run(應(yīng)用程序啟動(dòng)類.class)方法即可,那么SpringBoot是如何獲取當(dāng)前運(yùn)行環(huán)境呢,接下來由小編給大家介紹一下SpringBoot獲取當(dāng)前運(yùn)行環(huán)境三種方式,需要的朋友可以參考下2024-01-01mybatis中sql語句CDATA標(biāo)簽的用法說明
這篇文章主要介紹了mybatis中sql語句CDATA標(biāo)簽的用法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06