使用Jackson來實(shí)現(xiàn)Java對象與JSON的相互轉(zhuǎn)換的教程
一、入門
Jackson中有個ObjectMapper類很是實(shí)用,用于Java對象與JSON的互換。
1.JAVA對象轉(zhuǎn)JSON[JSON序列化]
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("小民");
user.setEmail("xiaomin@sina.com");
user.setAge(20);
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateformat.parse("1996-10-01"));
/**
* ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中實(shí)現(xiàn)。
* ObjectMapper有多個JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介質(zhì)中。
* writeValue(File arg0, Object arg1)把a(bǔ)rg1轉(zhuǎn)成json序列,并保存到arg0文件中。
* writeValue(OutputStream arg0, Object arg1)把a(bǔ)rg1轉(zhuǎn)成json序列,并保存到arg0輸出流中。
* writeValueAsBytes(Object arg0)把a(bǔ)rg0轉(zhuǎn)成json序列,并把結(jié)果輸出成字節(jié)數(shù)組。
* writeValueAsString(Object arg0)把a(bǔ)rg0轉(zhuǎn)成json序列,并把結(jié)果輸出成字符串。
*/
ObjectMapper mapper = new ObjectMapper();
//User類轉(zhuǎn)JSON
//輸出結(jié)果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
String json = mapper.writeValueAsString(user);
System.out.println(json);
//Java集合轉(zhuǎn)JSON
//輸出結(jié)果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}]
List<User> users = new ArrayList<User>();
users.add(user);
String jsonlist = mapper.writeValueAsString(users);
System.out.println(jsonlist);
}
}
2.JSON轉(zhuǎn)Java類[JSON反序列化]
import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
String json = "{\"name\":\"小民\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}";
/**
* ObjectMapper支持從byte[]、File、InputStream、字符串等數(shù)據(jù)的JSON反序列化。
*/
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
System.out.println(user);
}
}
二、Jackson支持3種使用方式:
1、Data Binding:最方便使用.
(1)Full Data Binding:
private static final String MODEL_BINDING = "{\"name\":\"name1\",\"type\":1}";
public void fullDataBinding() throws Exception{
ObjectMapper mapper = new ObjectMapper();
Model user = mapper.readValue(MODEL_BINDING, Model.class);//readValue到一個實(shí)體類中.
System.out.println(user.getName());
System.out.println(user.getType());
}
Model類:
private static class Model{
private String name;
private int type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
(2)Raw Data Binding:
/**
Concrete Java types that Jackson will use for simple data binding are:
JSON Type Java Type
object LinkedHashMap<String,Object>
array ArrayList<Object>
string String
number(no fraction) Integer, Long or BigInteger (smallest applicable)
number(fraction) Double(configurable to use BigDecimal)
true|false Boolean
null null
*/
public void rawDataBinding() throws Exception{
ObjectMapper mapper = new ObjectMapper();
HashMap map = mapper.readValue(MODEL_BINDING,HashMap.class);//readValue到一個原始數(shù)據(jù)類型.
System.out.println(map.get("name"));
System.out.println(map.get("type"));
}
(3)generic Data Binding:
private static final String GENERIC_BINDING = "{\"key1\":{\"name\":\"name2\",\"type\":2},\"key2\":{\"name\":\"name3\",\"type\":3}}";
public void genericDataBinding() throws Exception{
ObjectMapper mapper = new ObjectMapper();
HashMap<String,Model> modelMap = mapper.readValue(GENERIC_BINDING,new TypeReference<HashMap<String,Model>>(){});//readValue到一個范型數(shù)據(jù)中.
Model model = modelMap.get("key2");
System.out.println(model.getName());
System.out.println(model.getType());
}
2、Tree Model:最靈活。
private static final String TREE_MODEL_BINDING = "{\"treekey1\":\"treevalue1\",\"treekey2\":\"treevalue2\",\"children\":[{\"childkey1\":\"childkey1\"}]}";
public void treeModelBinding() throws Exception{
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(TREE_MODEL_BINDING);
//path與get作用相同,但是當(dāng)找不到該節(jié)點(diǎn)的時候,返回missing node而不是Null.
String treekey2value = rootNode.path("treekey2").getTextValue();//
System.out.println("treekey2value:" + treekey2value);
JsonNode childrenNode = rootNode.path("children");
String childkey1Value = childrenNode.get(0).path("childkey1").getTextValue();
System.out.println("childkey1Value:"+childkey1Value);
//創(chuàng)建根節(jié)點(diǎn)
ObjectNode root = mapper.createObjectNode();
//創(chuàng)建子節(jié)點(diǎn)1
ObjectNode node1 = mapper.createObjectNode();
node1.put("nodekey1",1);
node1.put("nodekey2",2);
//綁定子節(jié)點(diǎn)1
root.put("child",node1);
//數(shù)組節(jié)點(diǎn)
ArrayNode arrayNode = mapper.createArrayNode();
arrayNode.add(node1);
arrayNode.add(1);
//綁定數(shù)組節(jié)點(diǎn)
root.put("arraynode", arrayNode);
//JSON讀到樹節(jié)點(diǎn)
JsonNode valueToTreeNode = mapper.valueToTree(TREE_MODEL_BINDING);
//綁定JSON節(jié)點(diǎn)
root.put("valuetotreenode",valueToTreeNode);
//JSON綁定到JSON節(jié)點(diǎn)對象
JsonNode bindJsonNode = mapper.readValue(GENERIC_BINDING, JsonNode.class);//綁定JSON到JSON節(jié)點(diǎn)對象.
//綁定JSON節(jié)點(diǎn)
root.put("bindJsonNode",bindJsonNode);
System.out.println(mapper.writeValueAsString(root));
}
3、Streaming API:最佳性能。
對于性能要求高的程序,推薦使用流API,否則使用其他方法
不管是創(chuàng)建JsonGenerator還是JsonParser,都是使用JsonFactory。
package com.jingshou.jackson;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class JacksonTest6 {
public static void main(String[] args) throws IOException {
JsonFactory jfactory = new JsonFactory();
/*** write to file ***/
JsonGenerator jGenerator = jfactory.createGenerator(new File(
"c:\\user.json"), JsonEncoding.UTF8);
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("name", "mkyong"); // "name" : "mkyong"
jGenerator.writeNumberField("age", 29); // "age" : 29
jGenerator.writeFieldName("messages"); // "messages" :
jGenerator.writeStartArray(); // [
jGenerator.writeString("msg 1"); // "msg 1"
jGenerator.writeString("msg 2"); // "msg 2"
jGenerator.writeString("msg 3"); // "msg 3"
jGenerator.writeEndArray(); // ]
jGenerator.writeEndObject(); // }
jGenerator.close();
/*** read from file ***/
JsonParser jParser = jfactory.createParser(new File("c:\\user.json"));
// loop until token equal to "}"
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("name".equals(fieldname)) {
// current token is "name",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getText()); // display mkyong
}
if ("age".equals(fieldname)) {
// current token is "age",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getIntValue()); // display 29
}
if ("messages".equals(fieldname)) {
jParser.nextToken(); // current token is "[", move next
// messages is array, loop until token equal to "]"
while (jParser.nextToken() != JsonToken.END_ARRAY) {
// display msg1, msg2, msg3
System.out.println(jParser.getText());
}
}
}
jParser.close();
}
}
相關(guān)文章
springboot項(xiàng)目整合mybatis并配置mybatis中間件的實(shí)現(xiàn)
這篇文章主要介紹了springboot項(xiàng)目整合mybatis并配置mybatis中間件的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Springboot Thymeleaf數(shù)字對象使用方法
這篇文章主要介紹了Springboot Thymeleaf數(shù)字對象使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2007-09-09
ThreadPoolExecutor中的submit()方法詳細(xì)講解
在使用線程池的時候,發(fā)現(xiàn)除了execute()方法可以執(zhí)行任務(wù)外,還發(fā)現(xiàn)有一個方法submit()可以執(zhí)行任務(wù),本文就詳細(xì)的介紹一下ThreadPoolExecutor中的submit()方法,具有一定的參考價值,感興趣的可以了解一下2022-04-04
從try-with-resources到ThreadLocal,優(yōu)化你的代碼編寫方式
這篇文章主要為大家介紹了從try-with-resources到ThreadLocal,優(yōu)化代碼的編寫方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
舉例講解Java中synchronized關(guān)鍵字的用法
這篇文章主要介紹了Java中synchronized關(guān)鍵字的用法,針對synchronized修飾方法的使用作出了簡單講解和演示,需要的朋友可以參考下2016-04-04
詳解使用Jenkins部署Spring Boot項(xiàng)目
這篇文章主要介紹了詳解使用Jenkins部署Spring Boot,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11

