有的语句需要try catch
或者 抛出
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>
ObjectMapper mapper = new ObjectMapper();
User user = new User("Tom","沈阳");
String json = mapper.writeValueAsString(user);
System.out.print(json); //输出:{"name":"Tom","city","沈阳"}
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,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<String> al = new ArrayList<String>();
al.add("Tom");
al.add("沈阳");
String json = mapper.writeValueAsString(al);
System.out.print(json); //输出:["TOM","SHENYANG"]
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":"上海"}
//]
String json = "{\"name\":\"Tom\",\"city\":\"沈阳\"}";
User user = mapper.readValue(json, User.class);
System.out.println(user);
HashMap<String,String> map = mapper.readValue(json, HashMap.class);
System.out.println(map);
Map<String,User> map= mapper.readValue(json, HashMap.class);
System.out.println(map);
ArrayList<String> list= mapper.readValue(json, ArrayList.class);
System.out.println(list);
List<User> list= mapper.readValue(json, ArrayList.class);
System.out.println(list);