写点什么

jackson 学习之二:jackson-core

  • 2022 年 5 月 04 日
  • 本文字数:3345 字

    阅读完需:约 11 分钟

  1. 增加一个 Pojo,对应的是一条推特消息:


package com.bolingcavalry.jacksondemo.beans;


/**


  • @Description: 推特消息 bean

  • @author: willzhao E-mail: zq2599@gmail.com

  • @date: 2020/7/4 16:24


*/


public class TwitterEntry {


/**


  • 推特消息 id


*/


long id;


/**


  • 消息内容


*/


String text; /**


  • 消息创建者


*/


int fromUserId;


/**


  • 消息接收者


*/


int toUserId;


/**


  • 语言类型


*/


String languageCode; public long getId() {


return id;


} public void setId(long id) {


this.id = id;


} public String getText() {


return text;


} public void setText(String text) {


this.text = text;


} public int getFromUserId() {


return fromUserId;


} public void setFromUserId(int fromUserId) {


this.fromUserId = fromUserId;


} public int getToUserId() {


return toUserId;


} public void setToUserId(int toUserId) {


this.toUserId = toUserId;


} public String getLanguageCode() {


return languageCode;


} public void setLanguageCode(String languageCode) {


this.languageCode = languageCode;


} public TwitterEntry() {


} public String toString() {


return "[Tweet, id: "+id+", text='"+text+"', from: "+fromUserId+", to: "+toUserId+", lang: "+languageCode+"]";


}}


  1. 以上就是准备工作了,接下来开始实战 jackson-core;

[](()JsonFactory 线程安全吗?

  1. JsonFactory 是否是线程安全的,这是编码前要弄清楚的问题,因为 JsonParser 和 JsonGenerator 的创建都离不开 JsonFactory;

  2. 如下图红框所示,jackson 官方文档中明确指出 JsonFactory 是线程安全的,可以放心的作为全局变量给多线程同时使用:



  1. 官方文 《一线大厂 Java 面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 档地址:http://fasterxml.github.io/jackson-core/javadoc/2.11/

[](()jackson-core 实战

  1. 新建子工程 core,pom.xml 如下:


<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


<parent>


<artifactId>jacksondemo</artifactId>


<groupId>com.bolingcavalry</groupId>


<version>1.0-SNAPSHOT</version>


<relativePath>../pom.xml</relativePath>


</parent>


<modelVersion>4.0.0</modelVersion>


<groupId>com.bolingcavalry</groupId>


<artifactId>core</artifactId>


<name>core</name>


<description>Demo project for jackson core use</description>


<build>


<plugins>


<plugin>


<groupId>org.apache.maven.plugins</groupId>


<artifactId>maven-compiler-plugin</artifactId>


<configuration>


<source>8</source>


<target>8</target>


</configuration>


</plugin>


</plugins>


</build>


<dependencies>


<dependency>


<groupId>com.fasterxml.jackson.core</groupId>


<artifactId>jackson-databind</artifactId>


</dependency>


<dependency>


<groupId>org.slf4j</groupId>


<artifactId>slf4j-log4j12</artifactId>


</dependency>


<dependency>


<groupId>commons-io</groupId>


<artifactId>commons-io</artifactId>


</dependency>


<dependency>


<groupId>org.apache.commons</groupId>


<artifactId>commons-lang3</artifactId>


</dependency>


<dependency>


<groupId>com.bolingcavalry</groupId>


<artifactId>beans</artifactId>


<version>${project.version}</version>


</dependency>


</dependencies>


</project>


  1. 新建 StreamingDemo 类,这里面是调用 jackson-core 的 API 进行序列化和反序列化的所有 demo,如下:


package com.bolingcavalry.jacksondemo.core;


import com.bolingcavalry.jacksondemo.beans.TwitterEntry;


import com.fasterxml.jackson.core.*;


import com.fasterxml.jackson.databind.ObjectMapper;


import org.apache.commons.io.IOUtils;


import org.apache.commons.lang3.StringUtils;


import org.slf4j.Logger;


import org.slf4j.LoggerFactory;


import java.io.ByteArrayOutputStream;


import java.io.IOException;


import java.net.URL;


/**


  • @Description: jackson 低阶方法的使用

  • @author: willzhao E-mail: zq2599@gmail.com

  • @date: 2020/7/4 15:50


*/


public class StreamingDemo {


private static final Logger logger = LoggerFactory.getLogger(StreamingDemo.class);


JsonFactory jsonFactory = new JsonFactory();


/**


  • 该字符串的值是个网络地址,该地址对应的内容是个 JSON


*/


final static String TEST_JSON_DATA_URL = "https://raw.githubusercontent.com/zq2599/blog_demos/master/files/twitteer_message.json";


/**


  • 用来验证反序列化的 JSON 字符串


*/


final static String TEST_JSON_STR = "{\n" +


" "id":1125687077,\n" +


" "text":"@stroughtonsmith You need to add a \"Favourites\" tab to TC/iPhone. Like what TwitterFon did. I can't WAIT for your Twitter App!! :) Any ETA?",\n" +


" "fromUserId":855523, \n" +


" "toUserId":815309,\n" +


" "languageCode":"en"\n" +


"}";


/**


  • 用来验证序列化的 TwitterEntry 实例


*/


final static TwitterEntry TEST_OBJECT = new TwitterEntry();


/**


  • 准备好 TEST_OBJECT 对象的各个参数


*/


static {


TEST_OBJECT.setId(123456L);


TEST_OBJECT.setFromUserId(101);


TEST_OBJECT.setToUserId(102);


TEST_OBJECT.setText("this is a message for serializer test");


TEST_OBJECT.setLanguageCode("zh");


}


/**


  • 反序列化测试(JSON -> Object),入参是 JSON 字符串

  • @param json JSON 字符串

  • @return

  • @throws IOException


*/


public TwitterEntry deserializeJSONStr(String json) throws IOException {


JsonParser jsonParser = jsonFactory.createParser(json);


if (jsonParser.nextToken() != JsonToken.START_OBJECT) {


jsonParser.close();


logger.error("起始位置没有大括号");


throw new IOException("起始位置没有大括号");


}


TwitterEntry result = new TwitterEntry();


try {


// Iterate over object fields:


while (jsonParser.nextToken() != JsonToken.END_OBJECT) {


String fieldName = jsonParser.getCurrentName();


logger.info("正在解析字段 [{}]", jsonParser.getCurrentName());


// 解析下一个


jsonParser.nextToken();


switch (fieldName) {


case "id":


result.setId(jsonParser.getLongValue());


break;


case "text":


result.setText(jsonParser.getText());


break;


case "fromUserId":


result.setFromUserId(jsonParser.getIntValue());


break;


case "toUserId":


result.setToUserId(jsonParser.getIntValue());


break;


case "languageCode":


result.setLanguageCode(jsonParser.getText());


break;


default:


logger.error("未知字段 '" + fieldName + "'");


throw new IOException("未知字段 '" + fieldName + "'");


}


}


} catch (IOException e) {


logger.error("反序列化出现异常 :", e);


} finally {


jsonParser.close(); // important to close both parser and underlying File reader


}


return result;


}


/**


  • 反序列化测试(JSON -> Object),入参是 JSON 字符串

  • @param url JSON 字符串的网络地址

  • @return

  • @throws IOException


*/


public TwitterEntry deserializeJSONFromUrl(String url) throws IOException {


// 从网络上取得 JSON 字符串


String json = IOUtils.toString(new URL(TEST_JSON_DATA_URL), JsonEncoding.UTF8.name());


logger.info("从网络取得 JSON 数据 :\n{}", json);


if(StringUtils.isNotBlank(json)) {


return deserializeJSONStr(json);


} else {


logger.error("从网络获取 JSON 数据失败");


return null;


}


}


/**


  • 序列化测试(Object -> JSON)

  • @param twitterEntry

  • @return 由对象序列化得到的 JSON 字符串


*/


public String serialize(TwitterEntry twitterEntry) throws IOException{


String rlt = null;


ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();


JsonGenerator jsonGenerator = jsonFactory.createGenerator(byteArrayOutputStream, JsonEncoding.UTF8);


try {


jsonGenerator.useDefaultPrettyPrinter();

用户头像

还未添加个人签名 2022.04.13 加入

还未添加个人简介

评论

发布
暂无评论
jackson学习之二:jackson-core_Java_爱好编程进阶_InfoQ写作社区