admin管理员组文章数量:1516870
关于在controller中json数据与对象,map,list的相互转换 jackson
关于在controller中json数据与对象,map,list的相互转换
步骤: 1.导入jackson相关jar包
- jackson-annotations.jar
- jackson-core.jar
- jackson-databind.jar
com.fasterxml.jackson.corejackson-core2.7.3com.fasterxml.jackson.corejackson-databind2.7.3com.fasterxml.jackson.corejackson-annotations2.7.3 --------------------------------------
2.创建jackson的核心对象:ObjectMapper ObjectMapper mapper = new ObjectMapper();
3.调用mapper的相关方法
对象转json
User user = new User("Tom","沈阳"); String json = mapper.writeValueAsString(user); System.out.print(json); //输出:
Map<String,String>转json
HashMap<String,String> map = new HashMap<String,String>(); map.put("name","Kris"); map.put("city","沈阳"); String json = mapper.writeValueAsString(map); System.out.print(json); //输出:{"city":"沈阳","name":"Kris"} (HashMap是无序的)
Map<String,Object>转json
Map<String,User> map = new HashMap<String,User>(); map1.put("01",new User("Tom","沈阳")); map1.put("02",new User("Kris","上海")); String json = mapper.writeValueAsString(map1); System.out.println(json); 输出: { "01":{"name":"Tom","city":"沈阳"}, "02":{"name":"Kris","city":"上海"} }
ArrayList转为json
ArrayList al = new ArrayList(); al.add("Tom"); al.add("沈阳"); String json = mapper.writeValueAsString(al); System.out.print(json); //输出:["TOM","SHENYANG"]
ArrayList转为json
ArrayList al = new ArrayList(); al.add(new User("Tom","沈阳")); al.add(new User("Kris","上海")); String json = mapper.writeValueAsString(al); System.out.print(json); 输出: [ {"name":"Tom","city":"沈阳"}, {"name":"Kris","city":"上海"} ]
json转对象 String json = "{"name":"Tom","city":"沈阳"}"; User user = mapper.readValue(json, User.class); System.out.println(user);
json转map<String,String>
HashMap<String,String> map = mapper.readValue(json, HashMap.class); System.out.println(map);
json转map<String,Object>
Map<String,User> map= mapper.readValue(json, HashMap.class); System.out.println(map);
json转list
ArrayList list= mapper.readValue(json, ArrayList.class); System.out.println(list);
json转list
List list= mapper.readValue(json, ArrayList.class); System.out.println(list);
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2020-03-24,如有侵权请联系 cloudcommunity@tencent 删除对象数据controllerlistmap本文标签: 关于在controller中json数据与对象mAPlist的相互转换 jackson
版权声明:本文标题:关于在controller中json数据与对象,map,list的相互转换 jackson 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.betaflare.com/biancheng/1749357404a2942645.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。


发表评论