本篇内容主要讲解“怎么用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\":\"命令次数\",\"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\"}]}}"; 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转换为实体类”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。