关于在controller中json数据与对象,map,list的相互转换 jackson

133 阅读1分钟

关于在controller中json数据与对象,map,list的相互转换

步骤:
1.导入jackson相关jar包

  • jackson-annotations.jar
  • jackson-core.jar
  • jackson-databind.jar

com.fasterxml.jackson.core jackson-core 2.7.3 com.fasterxml.jackson.core jackson-databind 2.7.3 com.fasterxml.jackson.core jackson-annotations 2.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);