本文主要是介绍ObjectMapper 解析 json,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先,net.sf.json.JSONObject.fromObject(json),解析josn字符串的时候,会存在浮点型数据误差的问题,如534733.92解析成
534733.94。建议使用 ObjectMapper
问题描述,在使用 ObjectMapper解析json数据的时候,json数据太多,只想解析需要的数据生成pojo对象。
解析的Class为Map, 可以先使用Object.class ,调试之后发现是 linkedHashMap类型。
Map map = objectMapper.readValue(json, Map.class);Object emp = map.get("empList");ArrayList<LinkedHashMap> list = (ArrayList<LinkedHashMap>)emp;LinkedHashMap linkedHashMap = list.get(0);System.out.println(linkedHashMap.get("ename"));
例,ParamVo中有empList,入参为 ParamVo生成的json字符串,如何只解析 empList 中的数据,转成对应的pojo对象。
public class MyTest {public static void main(String[] args) throws Exception{ObjectMapper objectMapper = new ObjectMapper();ParamVo paramVo = new ParamVo();paramVo.setCode("200");paramVo.setMesage("成功");List<Emp> emps = new ArrayList<>();emps.add(new Emp(1001,"zhangsan","java", new BigDecimal("10"),10));emps.add(new Emp(1003,"zhaoliu","php", new BigDecimal("30"),30));paramVo.setEmpList(emps);paramVo.setEmp(new Emp(1002,"lisi","c++", new BigDecimal("20"),20));//解析 ParamVo paramVo = new ParamVo(); 生成的json//paramVo========={"mesage":"成功","emp":{"empno":1002,"ename":"lisi","job":"c++","mgr":null,"hiredate":null,"sal":20,"comm":null,"deptno":20},"empList":[{"empno":1001,"ename":"zhangsan","job":"java","mgr":null,"hiredate":null,"sal":10,"comm":null,"deptno":10},{"empno":1003,"ename":"zhaoliu","job":"php","mgr":null,"hiredate":null,"sal":30,"comm":null,"deptno":30}]}String json = objectMapper.writeValueAsString(paramVo);System.out.println("paramVo========="+json);ParamVo paramVo1 = objectMapper.readValue(json, ParamVo.class);//解析 List<Emp> emps = new ArrayList<>(); 生成的json//empsString======[{"empno":1001,"ename":"zhangsan","job":"java","mgr":null,"hiredate":null,"sal":10,"comm":null,"deptno":10},{"empno":1003,"ename":"zhaoliu","job":"php","mgr":null,"hiredate":null,"sal":30,"comm":null,"deptno":30}]String empsString = objectMapper.writeValueAsString(emps);System.out.println("empsString======"+empsString);JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Emp.class);List<Emp> list = objectMapper.readValue(empsString, javaType);//入参的 json 为 ParamVo paramVo = new ParamVo(); 生成的json,但是内容太多,只想解析 empList 的内容,转成对应的pojo//思路,可以通过 Object object = objectMapper.readValue(json, Object.class); debug查看该json生成的数据结构,发现是LinkedHashMapMap map = objectMapper.readValue(json, Map.class);Object emp = map.get("empList");ArrayList<LinkedHashMap> empList = (ArrayList<LinkedHashMap>)emp;for(int i=0;i<empList.size();i++){LinkedHashMap linkedHashMap = empList.get(i);System.out.println(linkedHashMap.toString());//{empno=1001, ename=zhangsan, job=java, mgr=null, hiredate=null, sal=10, comm=null, deptno=10}//{empno=1003, ename=zhaoliu, job=php, mgr=null, hiredate=null, sal=30, comm=null, deptno=30}//已经拿到 empList 的map数据,就可以转换成pojo了}}
}
这篇关于ObjectMapper 解析 json的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!