如何用ObjectMapper将复杂Map转换为实体类
目录
- ObjectMapper将复杂Map转为实体类
- 背景
- 1.使用ObjectMapper要添加的依赖是
- 2.将复杂Map开始转换
- objectMapper 解析复杂json toMap
ObjectMapper将复杂Map转为实体类 【如何用ObjectMapper将复杂Map转换为实体类】
背景
用fastjson转换复杂Map是浅层的可以转 深层的转换为null.,这时候可以用jackson来转。
1.使用ObjectMapper要添加的依赖是
com.fasterxml.jackson.core jackson-databind2.8.3
2.将复杂Map开始转换
ObjectMapper mapper = new ObjectMapper(); Resource resource = mapper.convertValue(Map, Resource.class);
注意的点:实体类中的字段是驼峰的 首字母不能大写。
objectMapper 解析复杂json toMap
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 {MapmapSettings =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 blocke.printStackTrace(); } catch (JsonMappingException e) {// TODO Auto-generated catch blocke.printStackTrace(); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace(); }}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
推荐阅读
- 任时光绽放成六月繁花
- 我从来不做坏事
- 考研英语阅读终极解决方案——阅读理解如何巧拿高分
- 樱花雨
- 如何寻找情感问答App的分析切入点
- 拍照一年啦,如果你想了解我,那就请先看看这篇文章
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus使用queryWrapper如何实现复杂查询
- 人如果没梦想,和咸鱼有什么区别(自媒体时代把握住就能咸鱼翻身)
- 如何在Mac中的文件选择框中打开系统隐藏文件夹