Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象
ObjectMapper类是Jackson库的主要类。它称为ObjectMapper的原因是因为它将JSON映射到Java对象(反序列化),或将Java对象映射到JSON(序列化)。它使用JsonParser和JsonGenerator的实例实现JSON实际的读/写。
maven 安装
com.fasterxml.jackson.core
jackson-core
2.9.6
com.fasterxml.jackson.core
jackson-annotations
2.9.6
com.fasterxml.jackson.core
jackson-databind
2.9.6
Jackson ObjectMapper如何将JSON字段与Java字段匹配
三种方式
1.Jackson通过将JSON字段的名称与Java对象中的getter和setter方法相匹配,将JSON对象的字段映射到Java对象中的字段。Jackson删除了getter和setter方法名称的“get”和“set”部分,并将剩余名称的第一个字符转换为小写。
2.Jackson还可以通过java反射进行匹配
3.通过注解或者其它方式进行自定义的序列化和反序列化程序。
转Java对象
Read Object From JSON String
ObjectMapper objectMapper = new ObjectMapper();
String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
Car car = objectMapper.readValue(carJson, Car.class);
2.Read Object From JSON Reader
ObjectMapper objectMapper = new ObjectMapper();
String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 4 }";
Reader reader = new StringReader(carJson);
Car car = objectMapper.readValue(reader, Car.class);
3.Read Object From JSON File
ObjectMapper objectMapper = new ObjectMapper();
File file = new File("data/car.json");
Car car = objectMapper.readValue(file, Car.class);
Read Object From JSON via URL
ObjectMapper objectMapper = new ObjectMapper();
URL url = new URL("file:data/car.json");
Car car = objectMapper.readValue(url, Car.class);
本例使用的是文件URL,也可使用一个HTTP URL(如:http://jenkov.com/some-data.json ).
Read Object From JSON InputStream
ObjectMapper objectMapper = new ObjectMapper();
InputStream input = new FileInputStream("data/car.json");
Car car = objectMapper.readValue(input, Car.class);
6.Read Object From JSON Byte Array