jackson 的 ObjectMapper用法

ObjectMapper 主要用作java对象的json化和返json化

看示例:

public class ObjectMapperDemo {

    public ObjectMapper initObject(){
        ObjectMapper objectMapper = new ObjectMapper();
        // 转换为格式化的json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        //新增属性不报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper;
    }

    public static void main(String [] args) throws IOException {
        Person person = new Person(30, "qobin");
        ObjectMapper objectMapper = new ObjectMapperDemo().initObject();
        System.out.println(objectMapper.writeValueAsString(person));
        objectMapper.writeValue(new FileWriter(new File("E:\\demo.txt"), true), person);
    }
}

你可能感兴趣的:(java)