Jackson的使用

Jackson详细使用

Jackson 简介

Jackson 是一个简单基于 Java 应用库,Jackson 可以轻松的将 Java 对象转换成 json 对象和 xml 文档,同样也可以将 json、xml 转换成 Java 对象。Jackson 所依赖的 jar 包较少,简单易用并且性能也要相对高些,并且 Jackson 社区相对比较活跃,更新速度也比较快。

Jackson 特点

容易使用 - jackson API 提供了一个高层次外观,以简化常用的用例。
无需创建映射 - API提供了默认的映射大部分对象序列化。
性能高 - 快速,低内存占用,适合大型对象图表或系统。
干净的 JSON - jackson 创建一个干净和紧凑的 JSON 结果,这是让人很容易阅读。
不依赖 - 库不需要任何其他的库,除了 JDK。
开源代码 - jackson 是开源的,可以免费使用。

Jackson 注解

Jackson 类库包含了很多注解,可以让我们快速建立 Java 类与 JSON 之间的关系。

@JsonProperty

@JsonProperty 注解指定一个属性用于 JSON 映射,默认情况下映射的 JSON 属性与注解的属性名称相同,不过可以使用该注解的 value 值修改 JSON 属性名,该注解还有一个 index 属性指定生成 JSON 属性的顺序,如果有必要的话。

@JsonIgnore

@JsonIgnore 注解用于排除某个属性,这样该属性就不会被 Jackson 序列化和反序列化。

@JsonIgnoreProperties

@JsonIgnoreProperties 注解是类注解。在序列化为 JSON 的时候,@JsonIgnoreProperties({"prop1", "prop2"}) 会忽略 pro1 和 pro2 两个属性。在从 JSON 反序列化为 Java 类的时候,@JsonIgnoreProperties(ignoreUnknown=true) 会忽略所有没有 Getter 和 Setter 的属性。该注解在 Java 类和 JSON 不完全匹配的时候很有用。

@JsonIgnoreType

@JsonIgnoreType 也是类注解,会排除所有指定类型的属性。

@JsonPropertyOrder

@JsonPropertyOrder@JsonProperty 的 index 属性类似,指定属性序列化时的顺序。

@JsonRootName

@JsonRootName 注解用于指定 JSON 根属性的名称。

@JsonInclude

@JsonInclude(JsonInclude.Include.NON_NULL):对值为 null 的属性不进行序列化

@JsonFormat

添加到需要指定格式的日期属性上,指定日期属性序列化与反序列化时的格式。timezone = “GMT+8” 设置时区,表示 +8 小时,否则会少8小时。ObjectMapper 序列化 POJO 对象为 json 字符串时,Date 日期类型默认会转为 long 长整型,json 字符串反序列化为 POJO 时自动将长整型的日期转为 Date 类型。

@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class Book {

    private Integer id;
    private String title;
    private Float price;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date publish;
}    

加 @JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”, timezone = “GMT+8”)后序列号的结果
在这里插入图片描述

Jackson 使用实例

jackson-databind 内部依赖了 jackson-annotations 与 jackson-core,所以 Maven 应用时,只要导入 databind 一个,则同时也导入了 annotations 与 core 依赖。

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.0</version>
</dependency>

如果是springboot项目只需要引入web模块即可
在这里插入图片描述

对象的序列化与反序列化

package com.zysheep.hello.httpclient;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonTester {
    public static void main(String[] args) {
        // 创建 ObjectMapper 对象
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";

        try {
            // 反序列化 JSON 到对象
            Student student = mapper.readValue(jsonString, Student.class);
            System.out.println(student);

            // 序列化对象到 JSON
            String json = mapper.writeValueAsString(student);
            System.out.println(json);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class Student {
    private String name;
    private int age;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Student [ name: " + name + ", age: " + age + " ]";
    }
}

集合的序列化与反序列化

package com.zysheep.hello.httpclient;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonTester {
    public static void main(String[] args) {
        // 创建 ObjectMapper 对象
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = "{\"draw\":1,\"recordsTotal\":1,\"recordsFiltered\":1,\"data\":[{\"id\":33,\"title\":\"ad1\",\"subTitle\":\"ad1\",\"titleDesc\":\"ad1\",\"url\":\"https://sale.jd.com/act/XkCzhoisOMSW.html\",\"pic\":\"https://m.360buyimg.com/babel/jfs/t20164/187/1771326168/92964/b42fade7/5b359ab2N93be3a65.jpg\",\"pic2\":\"\",\"content\":\"<p><br></p>\"}],\"error\":null}";

        try {
            // 反序列化 JSON 到树
            JsonNode jsonNode = mapper.readTree(jsonString);

            // 从树中读取 data 节点
            JsonNode jsonData = jsonNode.findPath("data");
            System.out.println(jsonData);

            // 反序列化 JSON 到集合
            JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, TbContent.class);
            List<TbContent> tbContents = mapper.readValue(jsonData.toString(), javaType);
            for (TbContent tbContent : tbContents) {
                System.out.println(tbContent);
            }

            // 序列化集合到 JSON
            String json = mapper.writeValueAsString(tbContents);
            System.out.println(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class TbContent {
    private Long id;
    private String title;
    private String subTitle;
    private String titleDesc;
    private String url;
    private String pic;
    private String pic2;
    private String content;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }

    public String getTitleDesc() {
        return titleDesc;
    }

    public void setTitleDesc(String titleDesc) {
        this.titleDesc = titleDesc;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public String getPic2() {
        return pic2;
    }

    public void setPic2(String pic2) {
        this.pic2 = pic2;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "TbContent{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", subTitle='" + subTitle + '\'' +
                ", titleDesc='" + titleDesc + '\'' +
                ", url='" + url + '\'' +
                ", pic='" + pic + '\'' +
                ", pic2='" + pic2 + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}

ObjectMapper常用API

ObjectMapper 主要用于对 Java 对象(比如 POJO、List、Set、Map 等等)进行序列化与反序列化。ObjectMapper 除了能在 json 字符串与 Java 对象之间进行转换,还能将 json 字符串与 JsonNode 进行转换。

Java 对象与 Json 字符串的转换
String writeValueAsString(Object value)1、用于将任何 Java 对象(如 POJO、List、Set、Map等)序列化为 json 字符串,如果对象中某个属性的值为 null,则默认也会序列化为 null;2、如果 value 为 null,返回序列化的结果也返回 null
byte[] writeValueAsBytes(Object value)将 java 对象序列化为 字节数组
writeValue(File resultFile, Object value)将 java 对象序列化并输出指定文件中
writeValue(OutputStream out, Object value)将 java 对象序列化并输出到指定字节输出流中
writeValue(Writer w, Object value)将 java 对象序列化并输出到指定字符输出流中
T readValue(String content, Class valueType)1、从给定的 JSON 字符串反序列化为 Java 对象;2、content 为空或者为 null,都会报错3、valueType 表示反序列化的结果对象,可以是任何 java 对象,比如 POJO、List、Set、Map 等等.
T readValue(byte[] src, Class valueType)将 json 内容的字节数组反序列化为 java 对象
T readValue(File src, Class valueType)将本地 json 内容的文件反序列化为 java 对象
T readValue(InputStream src, Class valueType)将 json 内容的字节输入流反序列化为 java 对象
T readValue(Reader src, Class valueType)将 json 内容的字符输入流反序列化为 java 对象
T readValue(URL src, Class valueType)通过网络 url 地址将 json 内容反序列化为 java 对象
Json 字符串内容反序列化为 Json 节点对象
JsonNode readTree(String content)将 JSON 字符串反序列化为 JsonNode 对象,即 json 节点对象
JsonNode readTree(URL source)对网络上的 json 文件进行反序列化为 json 节点对象
JsonNode readTree(InputStream in)对 json 文件输入流进行反序列化为 json 节点对象
JsonNode readTree(byte[] content)对 json 字节数组反序列化为 json 节点对象
JsonNode readTree(File file)将本地 json 文件反序列为为 json 节点对象
Java 对象与 Json 节点对象的转换
T convertValue(Object fromValue, Class toValueType)将 Java 对象(如 POJO、List、Map、Set 等)序列化为 Json 节点对象
T treeToValue(TreeNode n, Class valueType)json 树节点对象转 Java 对象(如 POJO、List、Set、Map 等等)TreeNode 树节点是整个 json 节点对象模型的根接口。
 /**
     * POJO 对象转 json 字符串
     * String writeValueAsString(Object value)
     * 1、该方法可用于将任何 Java 值、对象序列化为 json 字符串,如果对象中某个属性的值为 null,则默认也会序列化为 null
     * 2、value 为 null,返回 null
     *
     * @throws JsonProcessingException
     */
    @Test
    public void writeValueAsString1() throws JsonProcessingException {
        User user = new User(1000, "张三", new Date(), null);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        System.out.println(json);
        //{"uId":1000,"uName":"张三","birthday":1594881355832,"price":null}
    }

    /**
     * String writeValueAsString(Object value)
     * 1、 Java 值、对象序列化为 json 字符串,value 可以是任意的 java 对象,比如 POJO、list、Map、Set 等等
     */
    @Test
    public void writeValueAsString2() {
        try {
            List<User> userList = new ArrayList<>(2);
            User user1 = new User(1000, "张三", null, 7777.88F);
            User user2 = new User(2000, "李四", new Date(), 9800.78F);
            userList.add(user1);
            userList.add(user2);

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(userList);
            //[{"uId":1000,"uName":"张三","birthday":null,"price":7777.88},{"uId":2000,"uName":"李四","birthday":1594882217908,"price":9800.78}]
            System.out.println(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * String writeValueAsString(Object value)
     * 1、 Java 值、对象序列化为 json 字符串,value 可以是任意的 java 对象,比如 POJO、list、Map、Set 等等
     */
    @Test
    public void writeValueAsString3() throws JsonProcessingException {
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("uId", 9527);
            dataMap.put("uName", "华安");
            dataMap.put("birthday", new Date());
            dataMap.put("price", 9998.45F);
            dataMap.put("marry", null);

            ObjectMapper objectMapper = new ObjectMapper();
            //{"birthday":1594884443501,"uId":9527,"uName":"华安","price":9998.45,"marry":null}
            String json = objectMapper.writeValueAsString(dataMap);
            System.out.println(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * writeValue(File resultFile, Object value)
     * 1、 Java java 对象,比如 POJO、list、Map、Set 等等 序列化并输出到指定文件中
     * 2、文件不存在时,会自动新建
     */
    @Test
    public void writeValueAsString4() throws JsonProcessingException {
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("uId", 9527);
            dataMap.put("uName", "华安2");
            dataMap.put("birthday", new Date());
            dataMap.put("price", 9998.45F);
            dataMap.put("marry", null);

            File homeDirectory = FileSystemView.getFileSystemView().getHomeDirectory();
            File jsonFile = new File(homeDirectory, "wmx2.json");

            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(jsonFile, dataMap);
            System.out.println("输出 json 文件:" + jsonFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * T readValue(String content, Class<T> valueType)
     * 1、从给定的 JSON 内容字符串反序列化为对象
     * 2、content 为空或者为 null,都会报错
     * 3、valueType 表示反序列号的结果对象,可以是任何 java 对象,比如 POJO、List、Set、Map 等等.
     */
    @Test
    public void readValue1() {
        try {
            String json = "{\"uId\":1000,\"uName\":\"张三\",\"birthday\":1594881355832,\"price\":null}";
            ObjectMapper objectMapper = new ObjectMapper();
            User user = objectMapper.readValue(json, User.class);
            //User{uId=1000, uName='张三', birthday=Thu Jul 16 14:35:55 CST 2020, price=null}
            System.out.println(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * T readValue(String content, Class<T> valueType)
     * 1、从给定的 JSON 内容字符串反序列化为对象
     * 2、content 为空或者为 null,都会报错
     * 3、valueType 表示反序列号的结果对象,可以是任何 java 对象,比如 POJO、List、Set、Map 等等.
     */
    @Test
    public void readValue2() {
        try {
            String json = "[{\"uId\":1000,\"uName\":\"张三\",\"birthday\":null,\"price\":7777.88},{\"uId\":2000,\"uName\":\"李四\",\"birthday\":1594882217908,\"price\":9800.78}]";
            ObjectMapper objectMapper = new ObjectMapper();
            List<User> userList = objectMapper.readValue(json, List.class);
            //{uId=2000, uName=李四, birthday=1594882217908, price=9800.78}
            System.out.println(userList.get(1));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * T readValue(String content, Class<T> valueType)
     * 1、从给定的 JSON 内容字符串反序列化为对象
     * 2、content 为空或者为 null,都会报错
     * 3、valueType 表示反序列号的结果对象,可以是任何 java 对象,比如 POJO、List、Set、Map 等等.
     */
    @Test
    public void readValue3() {
        try {
            String json = "{\"birthday\":1594884443501,\"uId\":9527,\"uName\":\"华安\",\"price\":9998.45,\"marry\":null}";
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(json, Map.class);
            //{birthday=1594884443501, uId=9527, uName=华安, price=9998.45, marry=null}
            System.out.println(map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * T readValue(File src, Class<T> valueType):将本地 json 内容文件反序列为 Java 对象
     */
    @Test
    public void readTree4() {
        try {
            String json = "[{\"uId\":1000,\"uName\":\"张三\",\"birthday\":null,\"price\":7777.88},{\"uId\":2000,\"uName\":\"李四\",\"birthday\":1594882217908,\"price\":9800.78}]";
            File homeDirectory = FileSystemView.getFileSystemView().getHomeDirectory();
            File jsonFile = new File(homeDirectory, "wmx.json");
            if (!jsonFile.exists()) {
                FileWriter fileWriter = new FileWriter(jsonFile);
                fileWriter.write(json);
                fileWriter.flush();
                fileWriter.close();
                System.out.println("输出 json 文件:" + jsonFile.getAbsolutePath());
            }
            List<User> userList = new ObjectMapper().readValue(jsonFile, List.class);
            //{uId=2000, uName=李四, birthday=1594882217908, price=9800.78}
            System.out.println(userList.get(1));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * JsonNode readTree(String content):将 JSON 内容反序列化为 JsonNode 对象
     *
     * @throws IOException
     */
    @Test
    public void readTree1() throws IOException {
        //被解析的 json 格式的字符串
        String json = "{\"notices\":[{\"title\":\"停水\",\"day\":\"1\"},{\"title\":\"停电\",\"day\":\"3\"},{\"title\":\"停网\",\"day\":\"2\"}]}";
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(json);
        System.out.println(jsonNode);
    }

    /**
     * JsonNode readTree(URL source) :对网络上的 json 文件进行反序列化为 json 节点对象
     */
    @Test
    public void readTree2() {
        try {
            URL url = new URL("http://t.weather.sojson.com/api/weather/city/101030100");
            JsonNode jsonNode = new ObjectMapper().readTree(url);
            System.out.println(jsonNode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * JsonNode readTree(File file):将本地 json 文件反序列化为 json 节点对象
     */
    @Test
    public void readTree3() {
        try {
            String json = "[{\"uId\":1000,\"uName\":\"张三\",\"birthday\":null,\"price\":7777.88},{\"uId\":2000,\"uName\":\"李四\",\"birthday\":1594882217908,\"price\":9800.78}]";
            File homeDirectory = FileSystemView.getFileSystemView().getHomeDirectory();
            File jsonFile = new File(homeDirectory, "wmx.json");
            if (!jsonFile.exists()) {
                FileWriter fileWriter = new FileWriter(jsonFile);
                fileWriter.write(json);
                fileWriter.flush();
                fileWriter.close();
                System.out.println("输出 json 文件:" + jsonFile.getAbsolutePath());
            }
            JsonNode jsonNode = new ObjectMapper().readTree(jsonFile);
            System.out.println(jsonNode.get(0));//{"uId":1000,"uName":"张三","birthday":null,"price":7777.88}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * T treeToValue(TreeNode n, Class<T> valueType):json 节点对象转 Java 对象(如 POJO、List、Set、Map 等等)
     */
    @Test
    public void test() {
        try {
            ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
            objectNode.put("uId", 3200);
            objectNode.put("uName", "李世民");
            objectNode.put("birthday", new Date().getTime());

            User user = new ObjectMapper().treeToValue(objectNode, User.class);
            //User{uId=3200, uName='李世民', birthday=Fri Jul 17 20:34:13 CST 2020, price=null}
            System.out.println(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    /**
     * T convertValue(Object fromValue, Class<T> toValueType)
     * 1、将 Java 对象(如 POJO、List、Map、Set 等)序列化为 Json 节点对象,通常有以下两种方式:
     * 2、一种方式是先序列化为 json 字符串,然后 readTree 反序列化为 Json 节点
     * 3、还有就是使用此种方式进行转换,将 java 对象直接转换为 json 节点。
     */
    @Test
    public void convertValue1() {
        User user = new User(1000, "张三", new Date(), null);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.convertValue(user, JsonNode.class);
        //{"uId":1000,"uName":"张三","birthday":1594967015825,"price":null}
        System.out.println(jsonNode);
    }

    @Test
    public void convertValue2() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("uId", 9527);
        dataMap.put("uName", "华安");
        dataMap.put("birthday", new Date());
        dataMap.put("price", 9998.45F);
        dataMap.put("marry", null);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode objectNode = objectMapper.convertValue(dataMap, JsonNode.class);
        //{"birthday":1594950930586,"uId":9527,"uName":"华安","price":9998.45,"marry":null}
        System.out.println(objectNode);
    }

    @Test
    public void convertValue3() {
        List<User> userList = new ArrayList<>(2);
        User user1 = new User(1000, "张三", null, 7777.88F);
        User user2 = new User(2000, "李四", new Date(), 9800.78F);
        userList.add(user1);
        userList.add(user2);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode objectNode = objectMapper.convertValue(userList, JsonNode.class);
        //[{"uId":1000,"uName":"张三","birthday":null,"price":7777.88},{"uId":2000,"uName":"李四","birthday":1594967168878,"price":9800.78}]
        System.out.println(objectNode);
    }

JsonNode常用API

 /**
     * JsonNodeFactory.instance: 创建单例的 JsonNodeFactory 工厂
     * ObjectNode objectNode() : 构造空的 JSON 对象
     * ObjectNode put(String fieldName, String v): 将字段的值设置为指定的字符串值,如果字段已经存在,则更新值
     * ObjectNode put(String fieldName, int v):其它数据类型也是同理
     * ArrayNode putArray(String fieldName):构造 ArrayNode 并将其作为此 ObjectNode 的字段添加。
     * ObjectNode putNull(String fieldName): 为指定字段添加 null 值
     * ArrayNode add(String v) :将指定的字符串值添加到此数组的末尾,其它数据类型也是同理。
     */
    @Test
    public void objectNode1() {
        JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance;
        ObjectNode objectNode = jsonNodeFactory.objectNode();
        objectNode.put("name", "张三");
        objectNode.put("age", 25);
        objectNode.putNull("marry");

        ArrayNode arrayNode = objectNode.putArray("urls");
        arrayNode.add("http://tomcat.org/tomcat.png#1");
        arrayNode.add("http://tomcat.org/tomcat.png#2");
        arrayNode.add("http://tomcat.org/tomcat.png#3");

        //{"name":"张三","age":25,"marry":null,"urls":["http://tomcat.org/tomcat.png#1","http://tomcat.org/tomcat.png#2","http://tomcat.org/tomcat.png#3"]}
        System.out.println(objectNode.toString());
    }

    @Test
    public void objectNode2() {
        JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance;
        ObjectNode objectNode_root = jsonNodeFactory.objectNode();
        ArrayNode arrayNode = objectNode_root.putArray("notices");

        ObjectNode objectNodeChild = jsonNodeFactory.objectNode();
        objectNodeChild.put("title", "放假通知");
        objectNodeChild.put("content", "寒假放假于本月3浩开始.");
        arrayNode.add(objectNodeChild);

        //{"notices":[{"title":"放假通知","content":"寒假放假于本月3浩开始."}]}
        System.out.println(objectNode_root);
    }

    /**
     * JsonNode replace(String fieldName, JsonNode value):将特定属性的值替换为传递的值,字段存在时更新,不存在时新增
     * JsonNode set(String fieldName, JsonNode value):设置指定属性的值为 json 节点对象,字段存在时更新,不存在时新增,类似 replace 方法
     * JsonNode setAll(Map<String,? extends JsonNode> properties):同时设置多个 json 节点
     */
    @Test
    public void objectNode3() {
        try {
            String json = "{\"notices\":[{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\"}]}";
            JsonNode jsonNode = new ObjectMapper().readTree(json);
            ObjectNode objectNode = (ObjectNode) jsonNode;

            ObjectNode node = JsonNodeFactory.instance.objectNode();
            node.put("code", 200);
            objectNode.set("status", node);
            //{"notices":[{"title":"放假通知","content":"寒假放假于本月3浩开始."}],"status":{"code":200}}
            System.out.println(objectNode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * JsonNode setAll(ObjectNode other):添加给定对象(other)的所有属性,重写这些属性的任何现有值
     */
    @Test
    public void objectNode4() {
        try {
            String json = "{\"notices\":[{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\"}]}";
            JsonNode jsonNode = new ObjectMapper().readTree(json);
            ObjectNode objectNode = (ObjectNode) jsonNode;

            ObjectNode node = JsonNodeFactory.instance.objectNode();
            node.put("code", 200);
            objectNode.setAll(node);
            //{"notices":[{"title":"放假通知","content":"寒假放假于本月3浩开始."}],"code":200}
            System.out.println(objectNode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * JsonNode get(String fieldName):
     * 1、用于访问对象节点的指定字段的值,如果此节点不是对象、或没有指定字段名的值,或没有这样名称的字段,则返回 null。
     * boolean isArray(): 判断此节点是否为 {@link ArrayNode} 数组节点
     * int size():获取数组节点的大小
     * int asInt():
     * 1、尝试将此节点的值转换为 int 类型,布尔值 false 转换为 0,true 转换为 1。
     * 2、如果不能转换为 int(比如值是对象或数组等结构化类型),则返回默认值 0 ,不会引发异常。
     * String asText():如果节点是值节点(isValueNode返回true),则返回容器值的有效字符串表示形式,否则返回空字符串。
     * 其它数据类型也是同理
     */
    @Test
    public void objectNode5() {
        try {
            String json = "{\"notices\":[{\"title\":\"停水\",\"day\":\"12\"},{\"title\":\"停电\",\"day\":\"32\"},{\"title\":\"停网\",\"day\":\"22\"}]}";
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode jsonNode = (ObjectNode) objectMapper.readTree(json);

            JsonNode notices = jsonNode.get("notices");
            if (notices != null && notices.isArray()) {
                for (int i = 0; i < notices.size(); i++) {
                    JsonNode childNode = notices.get(i);
                    String title = childNode.get("title").asText();
                    Integer day = childNode.get("day").asInt();
                    System.out.println((i + 1) + ":" + title + "\t" + day);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ArrayNode withArray(String propertyName): 将 json 节点转为 json 数组对象
     * ObjectNode with(String propertyName):将 json 节点转为 ObjectNode 对象
     */
    @Test
    public void objectNode6() {
        try {
            String json = "{\"notices\":[{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\"}]}";
            JsonNode jsonNode = new ObjectMapper().readTree(json);

            ObjectNode objectNode = (ObjectNode) jsonNode;
            ArrayNode arrayNode = objectNode.withArray("notices");
            for (int i = 0; i < arrayNode.size(); i++) {
                //{"title":"放假通知","content":"寒假放假于本月3浩开始."}
                JsonNode node = arrayNode.get(i);
                System.out.println(node);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * JsonNode remove(String fieldName):删除指定的 key,返回被删除的节点
     * JsonNode without(String fieldName):
     * ObjectNode remove(Collection<String> fieldNames):同时删除多个字段
     * ObjectNode without(Collection<String> fieldNames):同时删除多个字段
     * ObjectNode removeAll(): 删除所有字段属性
     */
    @Test
    public void objectNode7() {
        try {
            String json = "{\"notices\":[{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\"}]}";
            JsonNode jsonNode = new ObjectMapper().readTree(json);
            ObjectNode objectNode = (ObjectNode) jsonNode;

            JsonNode remove = objectNode.remove("notices");
            System.out.println(remove);//[{"title":"放假通知","content":"寒假放假于本月3浩开始."}]
            System.out.println(objectNode);//{}

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ObjectNode deepCopy():json 节点对象深度复制,相当于克隆
     * Iterator<String> fieldNames(): 获取 json 对象中的所有 key
     */
    @Test
    public void objectNode8() {
        try {
            String json = "{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\"}";
            JsonNode jsonNode = new ObjectMapper().readTree(json);
            ObjectNode objectNode = (ObjectNode) jsonNode;
            ObjectNode deepCopy = objectNode.deepCopy();
            deepCopy.put("summary", "同意");
            System.out.println(objectNode);//{"title":"放假通知","content":"寒假放假于本月3浩开始."}
            System.out.println(deepCopy);//{"title":"放假通知","content":"寒假放假于本月3浩开始.","summary":"同意"}

            Iterator<String> fieldNames = deepCopy.fieldNames();
            while (fieldNames.hasNext()) {
                String next = fieldNames.next();
                System.out.println(next + "=" + deepCopy.get(next));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void objectNode9() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("code", 200);
        dataMap.put("msg", "成功");

        ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
        objectNode.putPOJO("data", dataMap);

        System.out.println(objectNode);
        JsonNode jsonNode = objectNode.get("data");
    }

    /**
     * double asDouble(): 尝试将此节点的值转换为 double,布尔值转换为0.0(false)和1.0(true),字符串使用默认的Java 语言浮点数解析规则进行解析。
     * 如果表示不能转换为 double(包括对象和数组等结构化类型),则返回默认值 0.0,不会引发异常。
     * BigDecimal decimalValue() :返回此节点的浮点值 BigDecimal, 当且仅当此节点为数字时(isNumber 返回true),对于其他类型,返回 BigDecimal.ZERO
     */
    @Test
    public void test10() {
        ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
        objectNode.put("id", 1000);
        objectNode.put("salay", 15000.456);

        double salay = objectNode.get("salay").asDouble();
        BigDecimal bigDecimal = objectNode.get("salay").decimalValue();
        System.out.println(salay + "," + bigDecimal);//15000.456,15000.456
    }

    /**
     * boolean has(int index):检查此节点是否为数组节点,并是否含有指定的索引。
     * boolean has(String fieldName):检查此节点是否为 JSON 对象节点并包含指定属性的值。
     */
    @Test
    public void test11() {
        ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode();
        arrayNode.add(12).add("中国").addNull().add(345.5667);
        System.out.println(arrayNode);//[12,"中国",null,345.5667]

        System.out.println(arrayNode.has(1));//true
        System.out.println(arrayNode.has(2));//true
        System.out.println(arrayNode.has(4));//false
    }

    /**
     * Iterator<JsonNode> elements():如果该节点是JSON数组或对象节点,则访问此节点的所有值节点
     * 对于对象节点,不包括字段名(键),只包括值,对于其他类型的节点,返回空迭代器。
     */
    @Test
    public void test12() {
        try {
            String json = "{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\",\"id\":23400}";
            JsonNode jsonNode = new ObjectMapper().readTree(json);
            Iterator<JsonNode> elements = jsonNode.elements();
            while (elements.hasNext()) {
                JsonNode next = elements.next();
                //"放假通知" "寒假放假于本月3浩开始." 23400
                System.out.print(next + " ");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ArrayNode addAll(ArrayNode other): 用于添加给定数组的所有子节点
     */
    @Test
    public void test13() {
        try {
            String json = "[{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\"}]";
            JsonNode jsonNode = new ObjectMapper().readTree(json);

            ArrayNode rootArrayNode = JsonNodeFactory.instance.arrayNode();
            rootArrayNode.add(1000);
            if (jsonNode.isArray()) {
                ArrayNode arrayNode = (ArrayNode) jsonNode;
                rootArrayNode.addAll(arrayNode);
            }
            //[1000,{"title":"放假通知","content":"寒假放假于本月3浩开始."}]
            System.out.println(rootArrayNode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ArrayNode addNull() :该方法将在此数组节点的末尾添加空值。
     */
    @Test
    public void test14() {
        try {
            String json = "[{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\"}]";
            JsonNode jsonNode = new ObjectMapper().readTree(json);
            if (jsonNode.isArray()) {
                ArrayNode arrayNode = (ArrayNode) jsonNode;
                arrayNode.addNull();
                //[{"title":"放假通知","content":"寒假放假于本月3浩开始."},null]
                System.out.println(arrayNode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ArrayNode addArray(): 构造新的 ArrayNode 节点,并将其添加到此数组节点的末尾
     */
    @Test
    public void test15() {
        try {
            String json = "[{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\"}]";
            JsonNode jsonNode = new ObjectMapper().readTree(json);
            if (jsonNode.isArray()) {
                ArrayNode arrayNode = (ArrayNode) jsonNode;
                ArrayNode addArray = arrayNode.addArray();
                addArray.add(31.4F);
                addArray.add("优秀");
                //[{"title":"放假通知","content":"寒假放假于本月3浩开始."},[31.4,"优秀"]]
                System.out.println(arrayNode);
                //[31.4,"优秀"]
                System.out.println(addArray);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ObjectNode putObject(String fieldName):构造新的 ObjectNode 字节的,并将其作为此 ObjectNode 的字段添加。
     */
    @Test
    public void test16() {
        try {
            String json = "{\"title\":\"放假通知\",\"content\":\"寒假放假于本月3浩开始.\"}";
            JsonNode jsonNode = new ObjectMapper().readTree(json);
            if (jsonNode.isObject()) {
                ObjectNode objectNode = (ObjectNode) jsonNode;
                ObjectNode persons = objectNode.putObject("person");
                persons.put("name", "张三");
                persons.put("age", 34);
                //{"title":"放假通知","content":"寒假放假于本月3浩开始.","person":{"name":"张三","age":34}}
                System.out.println(objectNode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

JackJsonUtil

@Slf4j
public class JackJsonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();

    // 时间日期格式
    private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";

    //以静态代码块初始化
    static {
        //对象的所有字段全部列入序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        //取消默认转换timestamps形式
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //忽略空Bean转json的错误
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //所有的日期格式都统一为以下的格式,即yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
        //忽略 在json字符串中存在,但在java对象中不存在对应属性的情况。防止错误
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    /**===========================以下是从JSON中获取对象====================================*/
    public static <T> T parseObject(String jsonString, Class<T> object) {
        T t = null;
        try {
            t = objectMapper.readValue(jsonString, object);
        } catch (JsonProcessingException e) {
            log.error("JsonString转为自定义对象失败:{}", e.getMessage());
        }
        return t;
    }

    public static <T> T parseObject(File file, Class<T> object) {
        T t = null;
        try {
            t = objectMapper.readValue(file, object);
        } catch (IOException e) {
            log.error("从文件中读取json字符串转为自定义对象失败:{}", e.getMessage());
        }
        return t;
    }

    //将json数组字符串转为指定对象List列表或者Map集合
    public static <T> T parseJSONArray(String jsonArray, TypeReference<T> reference) {
        T t = null;
        try {
            t = objectMapper.readValue(jsonArray, reference);
        } catch (JsonProcessingException e) {
            log.error("JSONArray转为List列表或者Map集合失败:{}", e.getMessage());
        }
        return t;
    }


    /**=================================以下是将对象转为JSON=====================================*/
    public static String toJSONString(Object object) {
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("Object转JSONString失败:{}", e.getMessage());
        }
        return jsonString;
    }

    public static byte[] toByteArray(Object object) {
        byte[] bytes = null;
        try {
            bytes = objectMapper.writeValueAsBytes(object);
        } catch (JsonProcessingException e) {
            log.error("Object转ByteArray失败:{}", e.getMessage());
        }
        return bytes;
    }

    public static void objectToFile(File file, Object object) {
        try {
            objectMapper.writeValue(file, object);
        } catch (JsonProcessingException e) {
            log.error("Object写入文件失败:{}", e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**=============================以下是与JsonNode相关的=======================================*/
    //JsonNode和JSONObject一样,都是JSON树形模型,只不过在jackson中,存在的是JsonNode
    public static JsonNode parseJSONObject(String jsonString) {
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(jsonString);
        } catch (JsonProcessingException e) {
            log.error("JSONString转为JsonNode失败:{}", e.getMessage());
        }
        return jsonNode;
    }

    public static JsonNode parseJSONObject(Object object) {
        JsonNode jsonNode = objectMapper.valueToTree(object);
        return jsonNode;
    }

    public static String toJSONString(JsonNode jsonNode) {
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(jsonNode);
        } catch (JsonProcessingException e) {
            log.error("JsonNode转JSONString失败:{}", e.getMessage());
        }
        return jsonString;
    }

    //JsonNode是一个抽象类,不能实例化,创建JSON树形模型,得用JsonNode的子类ObjectNode,用法和JSONObject大同小异
    public static ObjectNode newJSONObject() {
        return objectMapper.createObjectNode();
    }

    //创建JSON数组对象,就像JSONArray一样用
    public static ArrayNode newJSONArray() {
        return objectMapper.createArrayNode();
    }


    /**===========以下是从JsonNode对象中获取key值的方法,个人觉得有点多余,直接用JsonNode自带的取值方法会好点,出于纠结症,还是补充进来了*/
    public static String getString(JsonNode jsonObject, String key) {
        String s = jsonObject.get(key).asText();
        return s;
    }

    public static Integer getInteger(JsonNode jsonObject, String key) {
        Integer i = jsonObject.get(key).asInt();
        return i;
    }

    public static Boolean getBoolean(JsonNode jsonObject, String key) {
        Boolean bool = jsonObject.get(key).asBoolean();
        return bool;
    }

    public static JsonNode getJSONObject(JsonNode jsonObject, String key) {
        JsonNode json = jsonObject.get(key);
        return json;
    }
}

  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Spring Boot中使用Jackson库可以方便地进行JSON的序列化和反序列化操作。以下是使用Jackson的一些基本用法: 1. 添加Jackson依赖:在你的项目中,需要添加Jackson的依赖项。在`pom.xml`文件中,添加以下依赖项: ```xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency> ``` 2. 序列化对象为JSON使用`ObjectMapper`类可以将Java对象序列化为JSON字符串。例如,假设有一个名为`User`的Java类: ```java public class User { private String name; private int age; // 省略构造函数、getter和setter方法 @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } ``` 你可以使用以下代码将`User`对象序列化为JSON字符串: ```java import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws Exception { User user = new User("John Doe", 30); ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(user); System.out.println(json); } } ``` 3. 反序列化JSON为对象:使用`ObjectMapper`类可以将JSON字符串反序列化为Java对象。例如,假设有一个名为`User`的Java类: ```java public class User { private String name; private int age; // 省略构造函数、getter和setter方法 @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } ``` 你可以使用以下代码将JSON字符串反序列化为`User`对象: ```java import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws Exception { String json = "{\"name\":\"John Doe\",\"age\":30}"; ObjectMapper objectMapper = new ObjectMapper(); User user = objectMapper.readValue(json, User.class); System.out.println(user); } } ``` 以上是使用Jackson库进行基本的JSON序列化和反序列化操作的示例。你可以根据需要使用更多的Jackson功能,例如处理日期、自定义序列化器等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李熠漾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值