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

有的语句需要try catch或者 抛出

1.导入jackson相关jar包

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

maven依赖


 <dependency>
     <groupId>com.fasterxml.jackson.coregroupId>
     <artifactId>jackson-annotationsartifactId>
     <version>2.10.0version>
 dependency>
 
 <dependency>
     <groupId>com.fasterxml.jackson.coregroupId>
     <artifactId>jackson-coreartifactId>
     <version>2.10.0version>
 dependency>
 
 <dependency>
     <groupId>com.fasterxml.jackson.coregroupId>
     <artifactId>jackson-databindartifactId>
     <version>2.10.0version>
 dependency>

2.创建jackson的核心对象:ObjectMapper

ObjectMapper mapper = new ObjectMapper();

3.调用mapper的相关方法

3、1 对象转json

User user = new User("Tom","沈阳");
String json = mapper.writeValueAsString(user);
System.out.print(json); //输出:{"name":"Tom","city","沈阳"}

3、2 Map转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是无序的)

3、3 Map转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":"上海"}
//}

3、4 ArrayList转为json

ArrayList<String> al = new ArrayList<String>();
al.add("Tom");
al.add("沈阳");
String json = mapper.writeValueAsString(al);
System.out.print(json);  //输出:["TOM","SHENYANG"]

3、5 ArrayList转为json

ArrayList<User> al = new ArrayList<User>();
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":"上海"}
//]

3、6 json转对象

String json = "{\"name\":\"Tom\",\"city\":\"沈阳\"}";
User user = mapper.readValue(json, User.class);
System.out.println(user);

3、7 json转map

HashMap<String,String> map = mapper.readValue(json, HashMap.class);
System.out.println(map);

3、8 json转map

Map<String,User> map= mapper.readValue(json, HashMap.class);
System.out.println(map);

3、9 json转list

ArrayList<String> list= mapper.readValue(json, ArrayList.class);
System.out.println(list);

3、10 json转list

List<User> list= mapper.readValue(json, ArrayList.class);
System.out.println(list);

你可能感兴趣的:(Java,#,ssm)