这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos
名称 | 链接 | 备注 |
---|---|---|
项目主页 | https://github.com/zq2599/blog_demos | 该项目在GitHub上的主页 |
git仓库地址(https) | https://github.com/zq2599/blog_demos.git | 该项目源码的仓库地址,https协议 |
git仓库地址(ssh) | git@github.com:zq2599/blog_demos.git | 该项目源码的仓库地址,ssh协议 |
本文是《jackson学习》系列的第三篇,前面咱们学习了jackson的低阶API,知道了底层原理,本篇开始学习平时最常用的基本功能,涉及内容如下:
先看常用的序列化API:
String jsonStr = mapper.writeValueAsString(twitterEntry);
mapper.writeValue(new File("twitter.json"), twitterEntry);
byte[] array = mapper.writeValueAsBytes(twitterEntry);
TwitterEntry tFromStr = mapper.readValue(objectJsonStr, TwitterEntry.class);
TwitterEntry tFromFile = mapper.readValue(new File("twitter.json"), TwitterEntry.class);
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 URL(testJsonDataUrl), TwitterEntry.class);
String mapJsonStr = mapper.writeValueAsString(map);
Map<String, Object> mapFromStr = mapper.readValue(mapJsonStr, new TypeReference<Map<String, Object>>() {});
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();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
dateMapStr = mapper.writeValueAsString(dateMap);
假设jsonArrayStr是个json数组格式的字符串:
TwitterEntry[] twitterEntryArray = mapper.readValue(jsonArrayStr, TwitterEntry[].class);
List<TwitterEntry> twitterEntryList = mapper.readValue(jsonArrayStr, new TypeReference<List<TwitterEntry>>() {});
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 URL(testJsonDataUrl), TwitterEntry.class);
logger.info("从网络地址反序列化的对象:{}", tFromUrl);
logger.info("\n\n以下是集合序列化操作");
Map<String, Object> map = new HashMap<>();
map.put("name", "tom");
map.put("age", 11);
Map<String, String> 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<String, Object> mapFromStr = mapper.readValue(mapJsonStr, new TypeReference<Map<String, Object>>() {});
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<String, Object> 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<TwitterEntry> twitterEntryList = mapper.readValue(jsonArrayStr, new TypeReference<List<TwitterEntry>>() {});
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
{"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);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
{
"id" : 1,
"text" : "aabbcc",
"fromUserId" : 456,
"toUserId" : 0,
"languageCode" : "zh"
}
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
{
"aaa" : {
"id" : 1,
"text" : "aabbcc",
"fromUserId" : 456,
"toUserId" : 0,
"languageCode" : "zh"
}
}