VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Java教程 >
  • Java操作JSON数据(4,end)--Jackson操作JSON数据

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.abc.demo.general.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) + "]";
    }
}
复制代码
复制代码
package com.abc.demo.general.json;

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.*;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 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();
    }

}
复制代码

 

 
来源:https://www.cnblogs.com/wuyongyin/p/12017052.html


相关教程