1. 程式人生 > >Java之JSON操作(Jackson)

Java之JSON操作(Jackson)

單個 string not chan writev except java對象 tom ora

Java to JSON:
 1 package json.jackson;
 2 
 3 import bean.User;
 4 import com.fasterxml.jackson.databind.ObjectMapper;
 5 
 6 import java.io.File;
 7 import java.util.Map;
 8 
 9 /**
10  * Jackson – Java to JSON
11  * 功能:JSON與Java對象、Map等類型轉換,JSON文件的讀寫等
12  * 依賴包:jackson-databind-2.8.11.1.jar、jackson-core-2.8.10.jar、jackson-annotations-2.8.0.jar
13 * https://github.com/FasterXML/jackson-databind 14 */ 15 public class JavaToJSON { 16 public static void main(String[] ars) throws Exception { 17 User user = new User("tom", 25, "NO.1 street"); 18 ObjectMapper objectMapper = new ObjectMapper(); 19 20 // Java對象轉json,也支持bytes
21 String json = objectMapper.writeValueAsString(user); 22 System.out.println("Java對象轉json:" + json); 23 24 // json轉Java對象 25 User user2 = objectMapper.readValue(json, User.class); 26 System.out.println("json轉Java對象" + user2); 27 28 // 讀文件 29 String jsonFilePath = "src/main/java/json/jackson/JsonReader.json";
30 User user3 = objectMapper.readValue(new File(jsonFilePath), User.class); 31 System.out.println("讀取JSON文件:" + user3); 32 // 寫文件 33 objectMapper.writeValue(new File(jsonFilePath), user3); 34 35 // json轉map,也支持List 36 Map map = objectMapper.readValue(json, Map.class); 37 System.out.println("json轉map:" + map); 38 39 // map轉json字符串,支持所有類型轉字符串 40 String json2 = objectMapper.writeValueAsString(map); 41 System.out.println("map轉json:" + json2); 42 43 } 44 }
JsonNode:
 1 package json.jackson;
 2 
 3 import com.fasterxml.jackson.databind.JsonNode;
 4 import com.fasterxml.jackson.databind.ObjectMapper;
 5 
 6 import java.io.File;
 7 import java.util.List;
 8 
 9 /**
10  * JsonNode
11  * 處理復雜的JSON,返回多個對象的情況
12  * 從文件中讀取復雜的JSON,根據key找到對應value值
13  * 依賴包:jackson-databind-2.8.11.1.jar、jackson-core-2.8.10.jar、jackson-annotations-2.8.0.jar
14  * https://github.com/FasterXML/jackson-databind
15  */
16 public class JSONTreeDemo {
17     public static void main(String[] ars) throws Exception {
18         ObjectMapper objectMapper = new ObjectMapper();
19         String jsonFilePath = "src/main/java/json/jackson/Json2.json";
20         // 以樹形態支持多對象的情況:支持讀取多種類型
21         JsonNode jsonNode = objectMapper.readTree(new File(jsonFilePath));
22         System.out.println("jsonNode:" + jsonNode);
23         // 根據key查詢多個值,返回list
24         List<JsonNode> list = jsonNode.findValues("name");
25         System.out.println("Values:" + list);
26 
27         // 根據key查詢單個值
28         String channel = jsonNode.get("channel").asText();
29         System.out.println("查詢channel的值:" + channel);
30     }
31 }

Java之JSON操作(Jackson)