ObjectMapper基本用法

2018-09-09  本文已影响84人  07120665a058
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;
    }
}
ObjectMapper objectMapper = new ObjectMapper();
Product product = new Product("0001", "name", 1);
objectMapper.writeValue(new File("target/product.json"), product);
// 写入文件
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);
String jsonCarArray = "[{\"id\": \"0001\", \"name\" : \"Coca Cola\", \"price\": 3}]";

List<Product> listProduct =  productList = objectMapper.readValue(reader, new TypeReference<List<Product>>() {});
List  list = objectMapper.readValue(jsonCarArray, List.class);
String json = "{\"id\": \"0001\", \"name\" : \"Coca Cola\", \"price\": 3}";
Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){});
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
转换的类里面的getter方法必须是public的,才可以获取到

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

上一篇下一篇

猜你喜欢

热点阅读