Jackson

Jackson,第1张

Jackson
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
        List json_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>() {});
        // map -> json
        String map_to_json = objectMapper.writevalueAsString(json_to_map);

        // json -> jsonNode
        JsonNode json_to_jsonNode = objectMapper.readValue(json, JsonNode.class);
        // jsonNode -> json
        String jsonNode_to_json = objectMapper.writevalueAsString(json_to_jsonNode);

        // json -> objectNode
        ObjectNode json_to_objectNode = objectMapper.readValue(json, ObjectNode.class);
        // objectNode -> json
        String objectNode_to_json = objectMapper.writevalueAsString(json_to_jsonNode);
        
        // 获取某个字段的值(通过jsonNode/objectNode获取)
        if (json_to_jsonNode.has("name")) {
            JsonNode name = json_to_jsonNode.get("name");
            String nameForString = name.toString();
        }
        
        // 更多的方法看jsonNode源码
    }
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Person{
    private int id;
    private String name;
    
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5718017.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存