准备环境
@Data
. . .
public class City {
private int id;
private String name;
}
将简单对象转换为JSON字符串
public static void main ( String[ ] args) throws Exception {
City city = new City ( 1 , "深圳市" ) ;
ObjectMapper objectMapper = new ObjectMapper ( ) ;
String jsonStr = objectMapper. writeValueAsString ( city) ;
System. out. println ( jsonStr) ;
}
将简单对象JSON字符串转换为java对象
public static void main ( String[ ] args) throws Exception {
String jsonStr = "{\"id\":1,\"name\":\"深圳市\"}" ;
ObjectMapper objectMapper = new ObjectMapper ( ) ;
City city = objectMapper. readValue ( jsonStr, City. class ) ;
System. out. println ( city) ;
}
将List集合转换成JSON字符串
public static void main ( String[ ] args) throws Exception {
List< City> list = new ArrayList < > ( ) ;
list. add ( new City ( 1 , "深圳市" ) ) ;
list. add ( new City ( 2 , "汕头市" ) ) ;
list. add ( new City ( 3 , "广州市" ) ) ;
ObjectMapper objectMapper = new ObjectMapper ( ) ;
String jsonStr = objectMapper. writeValueAsString ( list) ;
System. out. println ( jsonStr) ;
}
将List集合JSON字符串转换为List对象
public static void main ( String[ ] args) throws Exception {
String jsonStr = "[{\"id\":1,\"name\":\"深圳市\"},{\"id\":2,\"name\":\"汕头市\"}, {\"id\":3,\"name\":\"广州市\"}]" ;
ObjectMapper objectMapper = new ObjectMapper ( ) ;
List list = objectMapper. readValue ( jsonStr, List. class ) ;
System. out. println ( list) ;
}
将Map集合转换为JSON字符串
public static void main ( String[ ] args) throws Exception {
Map< Integer, City> map = new HashMap < > ( ) ;
map. put ( 1 , new City ( 1 , "深圳市" ) ) ;
map. put ( 2 , new City ( 2 , "汕头市" ) ) ;
map. put ( 3 , new City ( 3 , "广州市" ) ) ;
String jsonStr = new ObjectMapper ( ) . writeValueAsString ( map) ;
System. out. println ( jsonStr) ;
}
将map集合JSON字符串转换为Map对象
public static void main ( String[ ] args) throws Exception {
String mapJson = "{\"1\":{\"id\":1,\"name\":\"深圳市\"},\"2\": {\"id\":2,\"name\":\"汕头市\"},\"3\":{\"id\":3,\"name\":\"广州市\"}}" ;
Map map = new ObjectMapper ( ) . readValue ( mapJson, Map. class ) ;
System. out. println ( map) ;
}