欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java操作JSON数据(4,end)--Jackson操作JSON数据

程序员文章站 2022-06-23 22:52:13
Jackson是SpringBoot默认使用的JSON处理库,它可以轻松的将Java对象转换成JSON对象,同样也可以将JSON转换成Java对象。本文介绍下Jackson的基本使用方法,包括序列化和反序列化;文中所使用到的软件版本:Java 1.8.0_191、Jackson 2.10.0。 1、 ......
jackson是springboot默认使用的json处理库,它可以轻松的将java对象转换成json对象,同样也可以将json转换成java对象。本文介绍下jackson的基本使用方法,包括序列化和反序列化;文中所使用到的软件版本:java 1.8.0_191、jackson 2.10.0。

1、引入依赖

<dependency>
  <groupid>com.fasterxml.jackson.core</groupid>
  <artifactid>jackson-core</artifactid>
  <version>2.10.0</version>
</dependency>
<dependency>
  <groupid>com.fasterxml.jackson.core</groupid>
  <artifactid>jackson-databind</artifactid>
  <version>2.10.0</version>
</dependency>
<dependency>
  <groupid>com.fasterxml.jackson.core</groupid>
  <artifactid>jackson-annotations</artifactid>
  <version>2.10.0</version>
</dependency>

如果使用的是springboot,默认就使用了jackson,则无需引入。

2、序列化

    public static string serialize() {
        mybean bean = new mybean();
        bean.sets("测试字符串");
        calendar calendar = calendar.getinstance();
        calendar.add(calendar.hour_of_day, -1);
        bean.setd(calendar.gettime());

        list<mybean> list = new arraylist<mybean>();
        list.add(bean);
        map<string, list<mybean>> map = new hashmap<string, list<mybean>>();
        map.put("data", list);
        string result = "";
        try {
            objectmapper objectmapper = new objectmapper();
            //设置日期格式,也可在类属性上使用@jsonformat(pattern="yyyy-mm-dd hh:mm:ss")来设置
            objectmapper.setdateformat(new simpledateformat("yyyy-mm-dd hh:mm:ss"));
            objectmapper.setserializationinclusion(include.always);
            //字符串如果为null则输出""
            objectmapper.setserializerfactory(objectmapper.getserializerfactory().withserializermodifier(new beanserializermodifier() {
                @override
                public list<beanpropertywriter> changeproperties(serializationconfig config, beandescription beandesc, list<beanpropertywriter> beanproperties) {
                    for (beanpropertywriter writer : beanproperties) {
                        class<?> clazz = writer.gettype().getrawclass();
                        if (charsequence.class.isassignablefrom(clazz) || character.class.isassignablefrom(clazz)) {
                            writer.assignnullserializer(new jsonserializer<object>() {
                                @override
                                public void serialize(object o, jsongenerator jsongenerator, serializerprovider serializerprovider) throws ioexception {
                                    jsongenerator.writestring("");
                                }
                            });
                        }
                    }
                    return beanproperties;
                }
            }));

            result = objectmapper.writevalueasstring(map);
            system.out.println(result);
        } catch (exception e) {
            e.printstacktrace();
        }

        return result;
    }

3、反序列化

    public static void deserialize() {
        string s = serialize();
        try {
            objectmapper objectmapper = new objectmapper();
            objectmapper.setdateformat(new simpledateformat("yyyy-mm-dd hh:mm:ss"));
            typereference<map<string, list<mybean>>> type = new typereference<map<string, list<mybean>>>(){};
            map<string, list<mybean>> map = objectmapper.readvalue(s, type);
            system.out.println(map);
            
            //树模型api
            jsonnode root = objectmapper.readtree(s);
            jsonnode bean = root.get("data").get(0);
            system.out.println(bean.get("s").astext());
            //...
        } catch (exception e) {
            e.printstacktrace();
        }
    }

4、完整例子

package com.inspur.demo.json;

import java.io.ioexception;
import java.text.simpledateformat;
import java.util.arraylist;
import java.util.calendar;
import java.util.hashmap;
import java.util.list;
import java.util.map;

import com.fasterxml.jackson.annotation.jsoninclude.include;
import com.fasterxml.jackson.core.jsongenerator;
import com.fasterxml.jackson.core.type.typereference;
import com.fasterxml.jackson.databind.beandescription;
import com.fasterxml.jackson.databind.jsonnode;
import com.fasterxml.jackson.databind.jsonserializer;
import com.fasterxml.jackson.databind.objectmapper;
import com.fasterxml.jackson.databind.serializationconfig;
import com.fasterxml.jackson.databind.serializerprovider;
import com.fasterxml.jackson.databind.ser.beanpropertywriter;
import com.fasterxml.jackson.databind.ser.beanserializermodifier;

/**
 * jackson操作json数据
 */
public class jacksoncase {
    /**
     * 序列化
     */
    public static string serialize() {
        mybean bean = new mybean();
        bean.sets("测试字符串");
        calendar calendar = calendar.getinstance();
        calendar.add(calendar.hour_of_day, -1);
        bean.setd(calendar.gettime());

        list<mybean> list = new arraylist<mybean>();
        list.add(bean);
        map<string, list<mybean>> map = new hashmap<string, list<mybean>>();
        map.put("data", list);
        string result = "";
        try {
            objectmapper objectmapper = new objectmapper();
            //设置日期格式,也可在类属性上使用@jsonformat(pattern="yyyy-mm-dd hh:mm:ss")来设置
            objectmapper.setdateformat(new simpledateformat("yyyy-mm-dd hh:mm:ss"));
            objectmapper.setserializationinclusion(include.always);
            //字符串如果为null则输出""
            objectmapper.setserializerfactory(objectmapper.getserializerfactory().withserializermodifier(new beanserializermodifier() {
                @override
                public list<beanpropertywriter> changeproperties(serializationconfig config, beandescription beandesc, list<beanpropertywriter> beanproperties) {
                    for (beanpropertywriter writer : beanproperties) {
                        class<?> clazz = writer.gettype().getrawclass();
                        if (charsequence.class.isassignablefrom(clazz) || character.class.isassignablefrom(clazz)) {
                            writer.assignnullserializer(new jsonserializer<object>() {
                                @override
                                public void serialize(object o, jsongenerator jsongenerator, serializerprovider serializerprovider) throws ioexception {
                                    jsongenerator.writestring("");
                                }
                            });
                        }
                    }
                    return beanproperties;
                }
            }));

            result = objectmapper.writevalueasstring(map);
            system.out.println(result);
        } catch (exception e) {
            e.printstacktrace();
        }

        return result;
    }

    /**
     * 反序列化
     */
    public static void deserialize() {
        string s = serialize();
        try {
            objectmapper objectmapper = new objectmapper();
            objectmapper.setdateformat(new simpledateformat("yyyy-mm-dd hh:mm:ss"));
            typereference<map<string, list<mybean>>> type = new typereference<map<string, list<mybean>>>(){};
            map<string, list<mybean>> map = objectmapper.readvalue(s, type);
            system.out.println(map);
            
            //树模型api
            jsonnode root = objectmapper.readtree(s);
            jsonnode bean = root.get("data").get(0);
            system.out.println(bean.get("s").astext());
            //...
        } catch (exception e) {
            e.printstacktrace();
        }
    }
    
    public static void main(string[] args) {
        serialize();
        deserialize();
    }

}
package com.inspur.demo.json;

import java.util.arrays;
import java.util.date;

public class mybean {
    private string s = "字符串";
    private string s2;
    private string s3 = "字符串3";
    private int i = 123;
    private integer i2;
    private char c = '到';
    private char[] c2 = new char[]{'a', 'b'};
    private date d = new date();
    private date[] d2 = new date[]{new date(), new date()};
    public string gets() {
        return s;
    }
    public void sets(string s) {
        this.s = s;
    }
    public string gets2() {
        return s2;
    }
    public void sets2(string s2) {
        this.s2 = s2;
    }
    public string gets3() {
        return s3;
    }
    public void sets3(string s3) {
        this.s3 = s3;
    }
    public int geti() {
        return i;
    }
    public void seti(int i) {
        this.i = i;
    }
    public integer geti2() {
        return i2;
    }
    public void seti2(integer i2) {
        this.i2 = i2;
    }
    public char getc() {
        return c;
    }
    public void setc(char c) {
        this.c = c;
    }
    public char[] getc2() {
        return c2;
    }
    public void setc2(char[] c2) {
        this.c2 = c2;
    }
    public date getd() {
        return d;
    }
    public void setd(date d) {
        this.d = d;
    }
    public date[] getd2() {
        return d2;
    }
    public void setd2(date[] d2) {
        this.d2 = d2;
    }
    @override
    public string tostring() {
        return "mybean [s=" + s + ", s2=" + s2 + ", s3=" + s3 + ", i=" + i + ", i2=" + i2 + ", c=" + c + ", c2="
                + arrays.tostring(c2) + ", d=" + d + ", d2=" + arrays.tostring(d2) + "]";
    }
}