public class TestJackson { static String jsonArray; static String json; static Person person; private static final ObjectMapper objectMapper; static { objectMapper = new ObjectMapper(); // 反序列化时,忽略json中存在但java对象不存在的属性 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) // 序列化日期格式 yyyy-MM-dd'T'HH:mm:ss.SSSZ .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) // 序列化时忽略值为 null 的属性 .setSerializationInclusion(JsonInclude.Include.NON_NULL) // 忽略值为默认值的属性 .setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT); // 初始化一些要用的值 person = new Person(); person.setId(1); person.setName("张三"); jsonArray = "[{"id":1,"name":"张三"},{"id":2,"name":"李四"}]"; json = "{"id":1,"name":"张三"}"; } public static void main(String[] args) throws Exception { // javaBean -> json String bean_to_json = objectMapper.writevalueAsString(person); // json -> javaBean Person json_to_bean = objectMapper.readValue(bean_to_json, Person.class); // json -> arrays Person[] json_to_array = objectMapper.readValue(jsonArray, Person[].class); // arrays -> json String arrys_to_json = objectMapper.writevalueAsString(json_to_array); // json -> list Listjson_to_list = objectMapper.readValue(jsonArray, new TypeReference >() {}); // list -> json String list_to_json = objectMapper.writevalueAsString(json_to_list); // json -> map Map
json_to_map = objectMapper.readValue(json, new TypeReference
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)