ObjectMapper基本用法

  • 定义一个Product类
class Product {
    private String id;
    private String name;
    private Integer price;
    public String getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public Integer getPrice() {
        return price;
    }
}
  • 将Java Object to JSON
ObjectMapper objectMapper = new ObjectMapper();
Product product = new Product("0001", "name", 1);
objectMapper.writeValue(new File("target/product.json"), product);
// 写入文件
  • 将 Json String 赋值给 一个类
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"id\": \"0001\", \"name\" : \"Coca Cola\", \"price\": 3}";

Product product = objectMapper.readValue(json, Product.class);

// product.getId();   0001
// 直接读取文件里面的值:
Product product = objectMapper.readValue(new File("target/json_car.json"), Product.class);
  • 将JSON Array String 赋值给List
String jsonCarArray = "[{\"id\": \"0001\", \"name\" : \"Coca Cola\", \"price\": 3}]";

List listProduct =  productList = objectMapper.readValue(reader, new TypeReference>() {});
List  list = objectMapper.readValue(jsonCarArray, List.class);
  • 将JSON String 赋值给map
String json = "{\"id\": \"0001\", \"name\" : \"Coca Cola\", \"price\": 3}";
Map map = objectMapper.readValue(json, new TypeReference>(){});
  • configure ObjectMapper to ignore unknown properties in the JSON
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
转换的类里面的getter方法必须是public的,才可以获取到

参考文章:
Intro to the Jackson ObjectMapper
Jackson ObjectMapper

你可能感兴趣的:(ObjectMapper基本用法)