應用Jackson來完成Java對象與JSON的互相轉換的教程。本站提示廣大學習愛好者:(應用Jackson來完成Java對象與JSON的互相轉換的教程)文章只能為提供參考,不一定能成為您想要的結果。以下是應用Jackson來完成Java對象與JSON的互相轉換的教程正文
1、入門
Jackson中有個ObjectMapper類很是適用,用於Java對象與JSON的交換。
1.JAVA對象轉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("[email protected]"); user.setAge(20); SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); user.setBirthday(dateformat.parse("1996-10-01")); /** * ObjectMapper是JSON操作的焦點,Jackson的一切JSON操作都是在ObjectMapper中完成。 * ObjectMapper有多個JSON序列化的辦法,可以把JSON字符串保留File、OutputStream等分歧的介質中。 * writeValue(File arg0, Object arg1)把arg1轉成json序列,並保留到arg0文件中。 * writeValue(OutputStream arg0, Object arg1)把arg1轉成json序列,並保留到arg0輸入流中。 * writeValueAsBytes(Object arg0)把arg0轉成json序列,並把成果輸入成字節數組。 * writeValueAsString(Object arg0)把arg0轉成json序列,並把成果輸入成字符串。 */ ObjectMapper mapper = new ObjectMapper(); //User類轉JSON //輸入成果:{"name":"小平易近","age":20,"birthday":844099200000,"email":"[email protected]"} String json = mapper.writeValueAsString(user); System.out.println(json); //Java聚集轉JSON //輸入成果:[{"name":"小平易近","age":20,"birthday":844099200000,"email":"[email protected]"}] List<User> users = new ArrayList<User>(); users.add(user); String jsonlist = mapper.writeValueAsString(users); System.out.println(jsonlist); } }
2.JSON轉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\":\"[email protected]\"}"; /** * ObjectMapper支撐從byte[]、File、InputStream、字符串等數據的JSON反序列化。 */ ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(json, User.class); System.out.println(user); } }
2、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到一個實體類中. 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到一個原始數據類型. 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到一個范型數據中. 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感化雷同,然則當找不到該節點的時刻,前往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); //創立根節點 ObjectNode root = mapper.createObjectNode(); //創立子節點1 ObjectNode node1 = mapper.createObjectNode(); node1.put("nodekey1",1); node1.put("nodekey2",2); //綁定子節點1 root.put("child",node1); //數組節點 ArrayNode arrayNode = mapper.createArrayNode(); arrayNode.add(node1); arrayNode.add(1); //綁定命組節點 root.put("arraynode", arrayNode); //JSON讀到樹節點 JsonNode valueToTreeNode = mapper.valueToTree(TREE_MODEL_BINDING); //綁定JSON節點 root.put("valuetotreenode",valueToTreeNode); //JSON綁定到JSON節點對象 JsonNode bindJsonNode = mapper.readValue(GENERIC_BINDING, JsonNode.class);//綁定JSON到JSON節點對象. //綁定JSON節點 root.put("bindJsonNode",bindJsonNode); System.out.println(mapper.writeValueAsString(root)); }
3、Streaming API:最好機能。
關於機能請求高的法式,推舉應用流API,不然應用其他辦法
不論是創立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(); } }