怎么用ObjectMapper将Map转换为实体类
生活随笔
收集整理的這篇文章主要介紹了
怎么用ObjectMapper将Map转换为实体类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本篇內容主要講解“怎么用ObjectMapper將Map轉換為實體類”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么用ObjectMapper將Map轉換為實體類”吧!
目錄
-
ObjectMapper將復雜Map轉為實體類
-
背景
-
1.使用ObjectMapper要添加的依賴是
-
2.將復雜Map開始轉換
-
objectMapper 解析復雜json toMap
ObjectMapper將復雜Map轉為實體類
背景
用fastjson轉換復雜Map是淺層的可以轉 深層的轉換為null.,這時候可以用jackson來轉。
1.使用ObjectMapper要添加的依賴是
<!--添加jackson包--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.3</version> </dependency>
2.將復雜Map開始轉換
ObjectMappermapper=newObjectMapper(); Resourceresource=mapper.convertValue(Map,Resource.class);
注意的點:實體類中的字段是駝峰的 首字母不能大寫。
objectMapper 解析復雜json toMap
publicvoidparseSettings(){
Stringsettings="{\"基本設置\":{\"name\":\"基本設置\",\"entries\":[{\"name\":\"站號\",\"type\":\"number\",\"description\":\"\",\"value\":\"1\"},{\"name\":\"AppEUI\",\"type\":\"string\",\"description\":\"\",\"value\":\"2C26C503A0010006\"},{\"name\":\"DevEUI\",\"type\":\"string\",\"description\":\"\",\"value\":\"4A7703A000FC09\"},{\"name\":\"命令次數\",\"type\":\"number\",\"description\":\"\",\"value\":\"2\"},{\"name\":\"父井號\",\"type\":\"string\",\"description\":\"\",\"value\":\"test11\"}]},\"油閥間\":{\"name\":\"油閥間\",\"entries\":[{\"name\":\"上傳間隔時間\",\"type\":\"number\",\"description\":\"\",\"value\":\"2\"},{\"name\":\"設定值\",\"type\":\"number\",\"description\":\"\",\"value\":\"10\"},{\"name\":\"波動值\",\"type\":\"number\",\"description\":\"\",\"value\":\"1\"},{\"name\":\"控制模式\",\"type\":\"number\",\"description\":\"\",\"value\":\"0\"},{\"name\":\"調節上限\",\"type\":\"number\",\"description\":\"\",\"value\":\"15\"},{\"name\":\"調節下限\",\"type\":\"number\",\"description\":\"\",\"value\":\"5\"},{\"name\":\"調節時間\",\"type\":\"number\",\"description\":\"\",\"value\":\"10\"}]},\"采集調度\":{\"name\":\"采集調度\",\"entries\":[{\"name\":\"interval\",\"type\":\"number\",\"description\":\"\",\"value\":\"2\"}]}}";
ObjectMapperobjectMapper=newObjectMapper();
JavaTypejavaType=objectMapper.getTypeFactory().constructMapType(HashMap.class,String.class,SettingGroup.class);
try{
Map<String,SettingGroup>mapSettings=objectMapper.readValue(settings,javaType);
SettingGroupgroup=mapSettings.get("基本設置");
for(SettingEntryentry:group.getEntries()){
System.out.println(entry.getName());
}
group=mapSettings.get("油閥間");
for(SettingEntryentry:group.getEntries()){
System.out.println("entry.Name:"+entry.getName()+"entry.getValue:"+entry.getValue());
}
}catch(JsonParseExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(JsonMappingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
總結
以上是生活随笔為你收集整理的怎么用ObjectMapper将Map转换为实体类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python处理xml文件_Python
- 下一篇: 疯狂html5+css3+javascr