Jackson库中ObjectMapper的用法

ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象与SON结构互相转换,在项目中遇到过,故记录一下。

在 pom.xml 加入依赖

<dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.8.3</version>
 </dependency>

创建一个实体类RiemannUser:

package com.test.objectMapper;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * @author riemann
 * @date 2019/05/27 22:48
 */
public class RiemannUser implements Serializable {

    private static final long serialVersionUID = 1L;

    private int id;

    private String message;

    private Date sendDate;

    private String nodeName;

    private List<Integer> intList;

    public RiemannUser() {
        super();
    }

    public RiemannUser(int id, String message, Date sendDate) {
        super();
        this.id = id;
        this.message = message;
        this.sendDate = sendDate;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public int getId() {
        return id;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Date getSendDate() {
        return sendDate;
    }

    public void setSendDate(Date sendDate) {
        this.sendDate = sendDate;
    }

    public String getNodeName() {
        return nodeName;
    }

    public void setNodeName(String nodeName) {
        this.nodeName = nodeName;
    }

    public List<Integer> getIntList() {
        return intList;
    }

    public void setIntList(List<Integer> intList) {
        this.intList = intList;
    }

    @Override
    public String toString() {
        return "RiemannUser{" + "id=" + id + ", message='" + message + '\'' + ", sendDate=" + sendDate + ", nodeName='" + nodeName + '\'' + ", intList=" + intList + '}';
    }

}

先创建一个ObjectMapper,然后赋值一些属性:

public static ObjectMapper mapper = new ObjectMapper();

static {
    // 转换为格式化的json
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    // 如果json中有新增的字段并且是实体类类中不存在的,不报错
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

1、对象与json字符串、byte数组

@Test
public void testObject() throws JsonGenerationException, JsonMappingException, IOException {
    RiemannUser riemann = new RiemannUser(1,"Hello World", new Date());
    mapper.writeValue(new File("D:/test.txt"), riemann);//写到文件中
    //mapper.writeValue(System.out, riemann); //写到控制台

    String jsonStr = mapper.writeValueAsString(riemann);
    System.out.println("对象转json字符串: " + jsonStr);

    byte[] byteArr = mapper.writeValueAsBytes(riemann);
    System.out.println("对象转为byte数组:" + byteArr);

    RiemannUser riemannUser = mapper.readValue(jsonStr, RiemannUser.class);
    System.out.println("json字符串转为对象:" + riemannUser);

    RiemannUser riemannUser2 = mapper.readValue(byteArr, RiemannUser.class);
    System.out.println("byte数组转为对象:" + riemannUser2);

}

运行结果:

对象转json字符串: {
  "id" : 1,
  "message" : "Hello World",
  "sendDate" : 1558971056693,
  "nodeName" : null,
  "intList" : null
}
对象转为byte数组:[B@31610302
json字符串转为对象:RiemannUser{id=1, message='Hello World', sendDate=Mon May 27 23:30:56 CST 2019, nodeName='null', intList=null}
byte数组转为对象:RiemannUser{id=1, message='Hello World', sendDate=Mon May 27 23:30:56 CST 2019, nodeName='null', intList=null}

2、list集合与json字符串

@Test
public void testList() throws JsonGenerationException, JsonMappingException, IOException {
    List<RiemannUser> riemannList = new ArrayList<>();
    riemannList.add(new RiemannUser(1,"a",new Date()));
    riemannList.add(new RiemannUser(2,"b",new Date()));
    riemannList.add(new RiemannUser(3,"c",new Date()));

    String jsonStr = mapper.writeValueAsString(riemannList);
    System.out.println("集合转为字符串:" + jsonStr);

    List<RiemannUser> riemannLists = mapper.readValue(jsonStr, List.class);
    System.out.println("字符串转集合:" + riemannLists);

}

运行结果:

集合转为字符串:[ {
  "id" : 1,
  "message" : "a",
  "sendDate" : 1558971833351,
  "nodeName" : null,
  "intList" : null
}, {
  "id" : 2,
  "message" : "b",
  "sendDate" : 1558971833351,
  "nodeName" : null,
  "intList" : null
}, {
  "id" : 3,
  "message" : "c",
  "sendDate" : 1558971833351,
  "nodeName" : null,
  "intList" : null
} ]
字符串转集合:[{id=1, message=a, sendDate=1558971833351, nodeName=null, intList=null}, {id=2, message=b, sendDate=1558971833351, nodeName=null, intList=null}, {id=3, message=c, sendDate=1558971833351, nodeName=null, intList=null}]

3、map与json字符串

@Test
public void testMap() {
    Map<String, Object> testMap = new HashMap<>();
    testMap.put("name", "riemann");
    testMap.put("age", 27);
    testMap.put("date", new Date());
    testMap.put("user", new RiemannUser(1, "Hello World", new Date()));

    String jsonStr = null;
    try {
        jsonStr = mapper.writeValueAsString(testMap);
        System.out.println("Map转为字符串:" + jsonStr);
        Map<String, Object> testMapDes = null;
        try {
            testMapDes = mapper.readValue(jsonStr, Map.class);
            System.out.println("字符串转Map:" + testMapDes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}
Map转为字符串:{
  "date" : 1558972169132,
  "name" : "riemann",
  "user" : {
    "id" : 1,
    "message" : "Hello World",
    "sendDate" : 1558972169134,
    "nodeName" : null,
    "intList" : null
  },
  "age" : 27
}
字符串转Map:{date=1558972169132, name=riemann, user={id=1, message=Hello World, sendDate=1558972169134, nodeName=null, intList=null}, age=27}

4、修改转换时的日期格式:

@Test
public void testOther() throws IOException {
    // 修改时间格式
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    RiemannUser riemannUser = new RiemannUser(1,"Hello World",new Date());
    riemannUser.setIntList(Arrays.asList(1,2,3));
    String jsonStr = mapper.writeValueAsString(riemannUser);
    System.out.println("对象转为字符串:" + jsonStr);
}

运行结果:

对象转为字符串:{
  "id" : 1,
  "message" : "Hello World",
  "sendDate" : "2019-05-27 23:53:55",
  "nodeName" : null,
  "intList" : [ 1, 2, 3 ]
}
收藏 (0)
评论列表
正在载入评论列表...
我是有底线的