凯发娱发k8

jackson学习之三:常用api操作 -凯发娱发k8

2023-08-17,,

欢迎访问我的github

https://github.com/zq2599/blog_demos

内容:所有原创文章分类汇总及配套源码,涉及java、docker、kubernetes、devops等;

系列文章汇总

jackson学习之一:基本信息
jackson学习之二:jackson-core
jackson学习:常用api
jackson学习之四:wrap_root_value(root对象)
jackson学习之五:jsoninclude注解
jackson学习之六:常用类注解
jackson学习之七:常用field注解
jackson学习之八:常用方法注解
jackson学习之九:springboot整合(配置文件)
jackson学习之十(终篇):springboot整合(配置类)

源码下载

    如果您不想编码,可以在github下载所有源码,地址和链接信息如下表所示(https://github.com/zq2599/blog_demos):
名称 链接 备注
项目凯发娱发k8主页 https://github.com/zq2599/blog_demos 该项目在github上的凯发娱发k8主页
git仓库地址(https) https://github.com/zq2599/blog_demos.git 该项目源码的仓库地址,https协议
git仓库地址(ssh) git@github.com:zq2599/blog_demos.git 该项目源码的仓库地址,ssh协议
    这个git项目中有多个文件夹,本章的应用在jacksondemo文件夹下,如下图红框所示:

本篇概览

本文是《jackson学习》系列的第三篇,前面咱们学习了jackson的低阶api,知道了底层原理,本篇开始学习平时最常用的基本功能,涉及内容如下:

    体验最常用的操作,内容如下图所示:
    介绍常用的可配置属性,以便按需要来设置;
    接下来进入快速浏览的环节,咱们一起先把各个api过一遍;

单个对象序列化

先看常用的序列化api:

    对象转字符串:
string jsonstr = mapper.writevalueasstring(twitterentry);
    对象转文件:
mapper.writevalue(new file("twitter.json"), twitterentry);
    对象转byte数组:
byte[] array = mapper.writevalueasbytes(twitterentry);

单个对象反序列化

    字符串转对象:
twitterentry tfromstr = mapper.readvalue(objectjsonstr, twitterentry.class);
    文件转对象:
twitterentry tfromfile = mapper.readvalue(new file("twitter.json"), twitterentry.class);
    byte数组转对象:
twitterentry tfrombytes = mapper.readvalue(array, twitterentry.class);
    字符串网络地址转对象:
string testjsondataurl = "https://raw.githubusercontent.com/zq2599/blog_demos/master/files/twitteer_message.json";
twitterentry tfromurl = mapper.readvalue(new , twitterentry.class);

集合序列化

    hashmap转字符串:
string mapjsonstr = mapper.writevalueasstring(map);

集合反序列化

    字符串转hashmap:
map mapfromstr = mapper.readvalue(mapjsonstr, new typereference>() {});

jsonnode

    如果您不想使用xxx.class来做反序列化,也能使用jsonnode来操作:
jsonnode jsonnode = mapper.readtree(mapjsonstr);
string name = jsonnode.get("name").astext();
int age = jsonnode.get("age").asint();
string city = jsonnode.get("addr").get("city").astext();
string street = jsonnode.get("addr").get("street").astext();

时间字段格式化

    对于date字段,默认的反序列化是时间戳,可以修改配置:
mapper.setdateformat(new simpledateformat("yyyy-mm-dd hh:mm:ss"));
datemapstr = mapper.writevalueasstring(datemap);

json数组的反序列化

假设jsonarraystr是个json数组格式的字符串:

    json数组转对象数组:
twitterentry[] twitterentryarray = mapper.readvalue(jsonarraystr, twitterentry[].class);
    json数组转对象集合(arraylist):
list twitterentrylist = mapper.readvalue(jsonarraystr, new typereference>() {});

完整代码

    上述所有常用api用法的完整代码如下:
package com.bolingcavalry.jacksondemo.databind;
import com.bolingcavalry.jacksondemo.beans.twitterentry;
import com.fasterxml.jackson.core.type.typereference;
import com.fasterxml.jackson.databind.jsonnode;
import com.fasterxml.jackson.databind.objectmapper;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import java.io.file;
import java.net.url;
import java.text.simpledateformat;
import java.util.*; public class simpledemo { private static final logger logger = loggerfactory.getlogger(simpledemo.class); public static void main(string[] args) throws exception {
objectmapper mapper = new objectmapper(); logger.info("以下是序列化操作"); // 对象 -> 字符串
twitterentry twitterentry = new twitterentry();
twitterentry.setid(123456l);
twitterentry.setfromuserid(101);
twitterentry.settouserid(102);
twitterentry.settext("this is a message for serializer test");
twitterentry.setlanguagecode("zh"); string jsonstr = mapper.writevalueasstring(twitterentry);
logger.info("序列化的字符串:{}", jsonstr); // 对象 -> 文件
mapper.writevalue(new file("twitter.json"), twitterentry); // 对象 -> byte数组
byte[] array = mapper.writevalueasbytes(twitterentry); logger.info("\n\n以下是反序列化操作"); // 字符串 -> 对象
string objectjsonstr = "{\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 tfromstr = mapper.readvalue(objectjsonstr, twitterentry.class);
logger.info("从字符串反序列化的对象:{}", tfromstr); // 文件 -> 对象
twitterentry tfromfile = mapper.readvalue(new file("twitter.json"), twitterentry.class);
logger.info("从文件反序列化的对象:{}", tfromstr); // byte数组 -> 对象
twitterentry tfrombytes = mapper.readvalue(array, twitterentry.class);
logger.info("从byte数组反序列化的对象:{}", tfrombytes); // 字符串网络地址 -> 对象
string testjsondataurl = "https://raw.githubusercontent.com/zq2599/blog_demos/master/files/twitteer_message.json"; twitterentry tfromurl = mapper.readvalue(new , twitterentry.class);
logger.info("从网络地址反序列化的对象:{}", tfromurl); logger.info("\n\n以下是集合序列化操作"); map map = new hashmap<>();
map.put("name", "tom");
map.put("age", 11); map addr = new hashmap<>();
addr.put("city","深圳");
addr.put("street", "粤海"); map.put("addr", addr); string mapjsonstr = mapper.writevalueasstring(map);
logger.info("hashmap序列化的字符串:{}", mapjsonstr); logger.info("\n\n以下是集合反序列化操作");
map mapfromstr = mapper.readvalue(mapjsonstr, new typereference>() {});
logger.info("从字符串反序列化的hashmap对象:{}", mapfromstr); // jsonnode类型操作
jsonnode jsonnode = mapper.readtree(mapjsonstr);
string name = jsonnode.get("name").astext();
int age = jsonnode.get("age").asint();
string city = jsonnode.get("addr").get("city").astext();
string street = jsonnode.get("addr").get("street").astext(); logger.info("用jsonnode对象和api反序列化得到的数:name[{}]、age[{}]、city[{}]、street[{}]", name, age, city, street); // 时间类型格式 map datemap = new hashmap<>();
datemap.put("today", new date()); string datemapstr = mapper.writevalueasstring(datemap);
logger.info("默认的时间序列化:{}", datemapstr); // 设置时间格式
mapper.setdateformat(new simpledateformat("yyyy-mm-dd hh:mm:ss"));
datemapstr = mapper.writevalueasstring(datemap);
logger.info("自定义的时间序列化:{}", datemapstr); system.out.println(objectjsonstr); // json数组
string jsonarraystr = "[{\n"
" \"id\":1,\n"
" \"text\":\"text1\",\n"
" \"fromuserid\":11, \n"
" \"touserid\":111,\n"
" \"languagecode\":\"en\"\n"
"},\n"
"{\n"
" \"id\":2,\n"
" \"text\":\"text2\",\n"
" \"fromuserid\":22, \n"
" \"touserid\":222,\n"
" \"languagecode\":\"zh\"\n"
"},\n"
"{\n"
" \"id\":3,\n"
" \"text\":\"text3\",\n"
" \"fromuserid\":33, \n"
" \"touserid\":333,\n"
" \"languagecode\":\"en\"\n"
"}]"; // json数组 -> 对象数组
twitterentry[] twitterentryarray = mapper.readvalue(jsonarraystr, twitterentry[].class);
logger.info("json数组反序列化成对象数组:{}", arrays.tostring(twitterentryarray)); // json数组 -> 对象集合
list twitterentrylist = mapper.readvalue(jsonarraystr, new typereference>() {});
logger.info("json数组反序列化成对象集合:{}", twitterentrylist);
}
}
    执行结果如下:
c:\jdk\bin\java.exe -javaagent:c:\sofware\jetbrains\intellijidea\lib\idea_rt.jar=64570:c:\sofware\jetbrains\intellijidea\bin -dfile.encoding=utf-8 -classpath c:\jdk\jre\lib\charsets.jar;c:\jdk\jre\lib\deploy.jar;c:\jdk\jre\lib\ext\access-bridge-64.jar;c:\jdk\jre\lib\ext\cldrdata.jar;c:\jdk\jre\lib\ext\dnsns.jar;c:\jdk\jre\lib\ext\jaccess.jar;c:\jdk\jre\lib\ext\jfxrt.jar;c:\jdk\jre\lib\ext\localedata.jar;c:\jdk\jre\lib\ext\nashorn.jar;c:\jdk\jre\lib\ext\sunec.jar;c:\jdk\jre\lib\ext\sunjce_provider.jar;c:\jdk\jre\lib\ext\sunmscapi.jar;c:\jdk\jre\lib\ext\sunpkcs11.jar;c:\jdk\jre\lib\ext\zipfs.jar;c:\jdk\jre\lib\javaws.jar;c:\jdk\jre\lib\jce.jar;c:\jdk\jre\lib\jfr.jar;c:\jdk\jre\lib\jfxswt.jar;c:\jdk\jre\lib\jsse.jar;c:\jdk\jre\lib\management-agent.jar;c:\jdk\jre\lib\plugin.jar;c:\jdk\jre\lib\resources.jar;c:\jdk\jre\lib\rt.jar;d:\github\blog_demos\jacksondemo\databind\target\classes;c:\users\12167\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.11.0\jackson-databind-2.11.0.jar;c:\users\12167\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.11.0\jackson-annotations-2.11.0.jar;c:\users\12167\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.11.0\jackson-core-2.11.0.jar;c:\users\12167\.m2\repository\org\slf4j\slf4j-log4j12\1.7.25\slf4j-log4j12-1.7.25.jar;c:\users\12167\.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;c:\users\12167\.m2\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar;c:\users\12167\.m2\repository\commons-io\commons-io\2.7\commons-io-2.7.jar;c:\users\12167\.m2\repository\org\apache\commons\commons-lang3\3.10\commons-lang3-3.10.jar;d:\github\blog_demos\jacksondemo\beans\target\classes com.bolingcavalry.jacksondemo.databind.simpledemo
2020-08-28 07:53:01 info simpledemo:27 - 以下是序列化操作
2020-08-28 07:53:01 info simpledemo:38 - 序列化的字符串:{"id":123456,"text":"this is a message for serializer test","fromuserid":101,"touserid":102,"languagecode":"zh"}
2020-08-28 07:53:01 info simpledemo:47 - 以下是反序列化操作
2020-08-28 07:53:01 info simpledemo:60 - 从字符串反序列化的对象:[tweet, id: 1125687077, 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?', from: 855523, to: 815309, lang: en]
2020-08-28 07:53:01 info simpledemo:64 - 从文件反序列化的对象:[tweet, id: 1125687077, 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?', from: 855523, to: 815309, lang: en]
2020-08-28 07:53:01 info simpledemo:68 - 从byte数组反序列化的对象:[tweet, id: 123456, text='this is a message for serializer test', from: 101, to: 102, lang: zh]
2020-08-28 07:53:04 info simpledemo:74 - 从网络地址反序列化的对象:[tweet, id: 112233445566, text='this is a message from zq2599's github', from: 201, to: 202, lang: en]
2020-08-28 07:53:04 info simpledemo:77 - 以下是集合序列化操作
2020-08-28 07:53:04 info simpledemo:90 - hashmap序列化的字符串:{"name":"tom","addr":{"city":"深圳","street":"粤海"},"age":11}
2020-08-28 07:53:04 info simpledemo:92 - 以下是集合反序列化操作
2020-08-28 07:53:04 info simpledemo:94 - 从字符串反序列化的hashmap对象:{name=tom, addr={city=深圳, street=粤海}, age=11}
2020-08-28 07:53:04 info simpledemo:103 - 用jsonnode对象和api反序列化得到的数:name[tom]、age[11]、city[深圳]、street[粤海]
2020-08-28 07:53:04 info simpledemo:111 - 默认的时间序列化:{"today":1598572384838}
2020-08-28 07:53:04 info simpledemo:116 - 自定义的时间序列化:{"today":"2020-08-28 07:53:04"}
{
"id":1125687077,
"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?",
"fromuserid":855523,
"touserid":815309,
"languagecode":"en"
}
2020-08-28 07:53:04 info simpledemo:145 - json数组反序列化成对象数组:[[tweet, id: 1, text='text1', from: 11, to: 111, lang: en], [tweet, id: 2, text='text2', from: 22, to: 222, lang: zh], [tweet, id: 3, text='text3', from: 33, to: 333, lang: en]]
2020-08-28 07:53:04 info simpledemo:149 - json数组反序列化成对象集合:[[tweet, id: 1, text='text1', from: 11, to: 111, lang: en], [tweet, id: 2, text='text2', from: 22, to: 222, lang: zh], [tweet, id: 3, text='text3', from: 33, to: 333, lang: en]] process finished with exit code 0
    还会产生名为twitter.json的文件,内容如下:
{"id":123456,"text":"this is a message for serializer test","fromuserid":101,"touserid":102,"languagecode":"zh"}

常用配置

下面是平时可能用到的自定义配置项目:

    序列化结果格式化:
mapper.enable(serializationfeature.indent_output);
    空对象不要抛出异常:
mapper.disable(serializationfeature.fail_on_empty_beans);
    date、calendar等序列化为时间格式的字符串(如果不执行以下设置,就会序列化成时间戳格式):
mapper.disable(serializationfeature.write_dates_as_timestamps);
    反序列化时,遇到未知属性不要抛出异常:
mapper.disable(deserializationfeature.fail_on_unknown_properties);
    反序列化时,空字符串对于的实例属性为null:
mapper.enable(deserializationfeature.accept_empty_string_as_null_object);
    允许c和c 样式注释:
mapper.configure(jsonparser.feature.allow_comments, true);
    允许字段名没有引号(可以进一步减小json体积):
mapper.configure(jsonparser.feature.allow_unquoted_field_names, true);
    允许单引号:
mapper.configure(jsonparser.feature.allow_single_quotes, true);

特殊配置:在json对象最外层再包裹一层

    最后要说的是个特殊配置,先来看看正常情况一个普通的序列化结果:
{
"id" : 1,
"text" : "aabbcc",
"fromuserid" : 456,
"touserid" : 0,
"languagecode" : "zh"
}
    接下来咱们做两件事,首先,是给上述json对应的实例类添加一个注解,如下图红框:

3. 其次,执行以下配置:

mapper.enable(serializationfeature.wrap_root_value);
    然后再次执行twitterentry实例的序列化,得到的结果如下,可见和之前的序列化结果相比,之前的整个json都变成了一个value,此value对应的key就是注解jsonrootname的value属性:
{
"aaa" : {
"id" : 1,
"text" : "aabbcc",
"fromuserid" : 456,
"touserid" : 0,
"languagecode" : "zh"
}
}

至此,开发中常用的api和配置都已经介绍完成,希望能给您带来一些参考,接下来的章节,咱们一起去了解另一个常用操作:jackson注解;

你不孤单,欣宸原创一路相伴

    java系列
    spring系列
    docker系列
    kubernetes系列
    数据库 中间件系列
    devops系列

欢迎关注公众号:程序员欣宸

微信搜索「程序员欣宸」,我是欣宸,期待与您一同畅游java世界...

https://github.com/zq2599/blog_demos

jackson学习之三:常用api操作的相关教程结束。

网站地图