美文网首页
ObjectMapper基本用法

ObjectMapper基本用法

作者: 07120665a058 | 来源:发表于2018-09-09 12:40 被阅读84次
    • 定义一个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<Product> listProduct =  productList = objectMapper.readValue(reader, new TypeReference<List<Product>>() {});
    List  list = objectMapper.readValue(jsonCarArray, List.class);
    
    • 将JSON String 赋值给map
    String json = "{\"id\": \"0001\", \"name\" : \"Coca Cola\", \"price\": 3}";
    Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){});
    
    • 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基本用法

          本文链接:https://www.haomeiwen.com/subject/iglaiftx.html