ObjectMapper mapper = new ObjectMapper(); Collection<Person> personResult = new ArrayList<Person>(); //将要发送给前台的数据放入map集合去 Map<String,Object> map = new HashMap<String,Object>(); map.put("person", personResult); map.put("departmentCount",50); //定义一个totalresult对象,封装map对象与记录 TotalResult totalResult = new TotalResult(); totalResult.setMap(map); totalResult.setTotalCount(2*personResult.size()+list.size()+(Integer)map.get("departmentCount")); //然后将totalresult序列化成json数据 return mapper.writeValueAsString(totalResult); //这是totalresult对象 //当前注解主要是为了让接收数据段得到的第一个数据key是totalcount //前台解析数据是边接收边解析(我认为,不然为什么要这样设置这样数据) @JsonPropertyOrder({"totalCount"}) public class TotalResult implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private Map<String,Object> map; private int totalCount; public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } //反序列化数据,因为jackson序列化对象都是键值对类型数据,所以反序列化数据我们可以当做是一个树形结构的json数据,然后我们可以读取对应的key就可以得到对应的值,然后根据自己当前定义的值是什么类型则声明什么类型的对象 ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(json); JsonNode jn = mapper.readTree(jsonMode.get("map")); String person = jn.get("person").toString(); String departmentCount = mapper.readTree(str).get("departmentCount ").toString(); //这里引用了一个typerefence,这个代表将数据转换成list<phoneperson>类型的集合数据,因为我们知道数据类型是这样的一个类型 List<PhonePerson> list = mapper.readValue(person, new TypeReference<List<PhonePerson>>(){}); //如果反序列化一般的对象则直接定义类类型 Person p = mapper.readValue(person,Person.class); //也可以反序列化数组对象 String str = "[{"groupId": "address2","personName":"haha2"},"+ "{"groupId":"address","personName":"haha"}]"; ObjectMapper mapper = new ObjectMapper(); PhonePerson[] pp = mapper.readValue(str, PhonePerson[].class); //将数据对象转换成集合对象 Collection<PhonePerson> list = Arrays.asList(pp); System.out.println(list.size()); for(PhonePerson p:list){ System.out.println(p.getPersonName()); }
使用json心得(第三方库jackson)
最新推荐文章于 2023-08-19 17:41:23 发布