您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“怎么用ObjectMapper將Map轉換為實體類”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么用ObjectMapper將Map轉換為實體類”吧!
ObjectMapper將復雜Map轉為實體類
背景
1.使用ObjectMapper要添加的依賴是
2.將復雜Map開始轉換
objectMapper 解析復雜json toMap
用fastjson轉換復雜Map是淺層的可以轉 深層的轉換為null.,這時候可以用jackson來轉。
<!--添加jackson包--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.3</version> </dependency>
ObjectMapper mapper = new ObjectMapper(); Resource resource = mapper.convertValue(Map, Resource.class);
注意的點:實體類中的字段是駝峰的 首字母不能大寫。
public void parseSettings(){ String settings = "{\"基本設置\":{\"name\":\"基本設置\",\"entries\":[{\"name\":\"站號\",\"type\":\"number\",\"description\":\"\",\"value\":\"1\"},{\"name\":\"AppEUI\",\"type\":\"string\",\"description\":\"\",\"value\":\"2C26C503A0010006\"},{\"name\":\"DevEUI\",\"type\":\"string\",\"description\":\"\",\"value\":\"4A7703A000FC09\"},{\"name\":\"命令次數(shù)\",\"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\":\"調節(jié)上限\",\"type\":\"number\",\"description\":\"\",\"value\":\"15\"},{\"name\":\"調節(jié)下限\",\"type\":\"number\",\"description\":\"\",\"value\":\"5\"},{\"name\":\"調節(jié)時間\",\"type\":\"number\",\"description\":\"\",\"value\":\"10\"}]},\"采集調度\":{\"name\":\"采集調度\",\"entries\":[{\"name\":\"interval\",\"type\":\"number\",\"description\":\"\",\"value\":\"2\"}]}}"; ObjectMapper objectMapper = new ObjectMapper(); JavaType javaType = objectMapper.getTypeFactory().constructMapType(HashMap.class, String.class, SettingGroup.class); try { Map<String,SettingGroup> mapSettings = objectMapper.readValue(settings, javaType); SettingGroup group = mapSettings.get("基本設置"); for (SettingEntry entry : group.getEntries()) { System.out.println(entry.getName()); } group = mapSettings.get("油閥間"); for (SettingEntry entry : group.getEntries()) { System.out.println("entry.Name:"+entry.getName()+" entry.getValue:"+entry.getValue()); } } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
到此,相信大家對“怎么用ObjectMapper將Map轉換為實體類”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。