Java基礎-處理json字串解析案例
作者:尹正傑
版權宣告:原創作品,謝絕轉載!否則將追究法律責任。
作為一名開發人員,想必大家或多或少都有接觸到XML檔案,XML全稱為“extensible markup language”,即可擴充套件性標記語言。它由於可讀性很好,但是在網路傳輸上,這種資料格式往往很佔用頻寬等諸多缺點,因此就誕生了Json,它比XML資料更小、更快、更容易解析。資料由名稱-值 對錶示,由逗號分隔開,花括號儲存物件,方括號儲存陣列。Json值可以是:數字/字串/邏輯值/陣列/物件/null。
接下來我們就一起看看如何建立一個json檔案以及如何解析json檔案。
一.java自定義物件物件和json字串的互轉
1>.新增Maven依賴(新增最後一個依賴json即可)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>groupId</groupId> 8 <artifactId>MyHadoop</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 11 <dependencies> 12 <dependency> 13 <groupId>org.apache.hadoop</groupId> 14 <artifactId>hadoop-client</artifactId> 15 <version>2.7.3</version> 16 </dependency> 17 18 <!-- https://mvnrepository.com/artifact/junit/junit --> 19 <dependency> 20 <groupId>junit</groupId> 21 <artifactId>junit</artifactId> 22 <version>4.12</version> 23 <scope>test</scope> 24 </dependency> 25 26 <dependency> 27 <groupId>mysql</groupId> 28 <artifactId>mysql-connector-java</artifactId> 29 <version>5.1.17</version> 30 </dependency> 31 <dependency> 32 <groupId>com.alibaba</groupId> 33 <artifactId>fastjson</artifactId> 34 <version>1.2.47</version> 35 </dependency> 36 37 </dependencies> 38 39 </project>
2>.具體實現程式碼如下:
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 public class Teacher { 9 private String name; 10 private int age; 11 12 public Teacher(String name, int age) { 13 this.name = name; 14 this.age = age; 15 } 16 17 public Teacher() { 18 } 19 20 public String getName() { 21 return name; 22 } 23 24 public void setName(String name) { 25 this.name = name; 26 } 27 28 public int getAge() { 29 return age; 30 } 31 32 public void setAge(int age) { 33 this.age = age; 34 } 35 36 public String toString() { 37 return "Teacher{" + "name='" + name + ", age=" + age + '}'; 38 } 39 }
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 import com.alibaba.fastjson.JSONObject; 9 10 import java.io.FileInputStream; 11 import java.io.FileOutputStream; 12 import java.io.IOException; 13 14 public class JsonOperation { 15 public static final String filePath = "D:\\10.Java\\IDE\\yhinzhengjieData\\MyHadoop\\JSON\\teacher.txt"; 16 17 public static void main(String[] args) throws Exception { 18 generatingJSON(); 19 System.out.println("=============我是分割線============="); 20 parsingJSON(); 21 } 22 //生成json文字 23 private static void generatingJSON() throws IOException { 24 Teacher yzj = new Teacher("尹正傑", 18); 25 String json = JSONObject.toJSONString(yzj); 26 System.out.println(json); 27 FileOutputStream fos = new FileOutputStream(filePath); 28 byte[] buf = new byte[1024]; 29 fos.write(json.getBytes()); 30 fos.close(); 31 } 32 33 //解析json文字 34 private static void parsingJSON() throws IOException { 35 byte[] buf = new byte[1024]; 36 FileInputStream fis = new FileInputStream(filePath); 37 //由於我的檔案較小,為了實驗方便我就一次性讀取出來了 38 JSONObject json = JSONObject.parseObject( new String(buf,0,fis.read(buf))); 39 System.out.println(json); 40 } 41 } 42 43 44 45 46 /* 47 以上程式碼執行結果如下: 48 {"age":18,"name":"尹正傑"} 49 =============我是分割線============= 50 {"name":"尹正傑","age":18} 51 */
二.Java資料型別和Json互相轉換案例
以下是list和json字串的互轉,當然,map的轉換json和其方法類似,我這裡就不多舉例了:
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 public class Teacher { 9 private String name; 10 private int age; 11 12 public Teacher(String name, int age) { 13 this.name = name; 14 this.age = age; 15 } 16 17 public Teacher() { 18 } 19 20 public String getName() { 21 return name; 22 } 23 24 public void setName(String name) { 25 this.name = name; 26 } 27 28 public int getAge() { 29 return age; 30 } 31 32 public void setAge(int age) { 33 this.age = age; 34 } 35 36 public String toString() { 37 return "Teacher{" + "name='" + name + ", age=" + age + '}'; 38 } 39 }
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 import com.alibaba.fastjson.JSON; 9 import com.alibaba.fastjson.JSONArray; 10 import com.alibaba.fastjson.JSONObject; 11 12 import java.util.ArrayList; 13 import java.util.List; 14 15 public class JsonOperation { 16 17 18 public static void main(String[] args) throws Exception { 19 listToJSON(); 20 System.out.println("=============我是分割線============="); 21 jsonToList(); 22 } 23 public static void listToJSON(){ 24 Teacher yzj = new Teacher("尹正傑",18); 25 Teacher yzj1 = new Teacher("yinzhengjie",19); 26 Teacher yzj2 = new Teacher("YINZHENGJIE",20); 27 List<Teacher> lists=new ArrayList<Teacher>(); 28 lists.add(yzj); 29 lists.add(yzj1); 30 lists.add(yzj2); 31 String listArray=JSONArray.toJSONString(lists); 32 System.out.println("arrayList:"+listArray); 33 } 34 35 public static void jsonToList(){ 36 String str ="{\"names\":[\"尹正傑\",\"yinzhengjie\"]}"; 37 JSONObject jo = JSON.parseObject(str); 38 JSONArray jsonArray = jo.getJSONArray("names"); 39 for (Object o : jsonArray) { 40 System.out.println(o.toString()); 41 } 42 } 43 } 44 45 /* 46 以上程式碼執行結果如下: 47 arrayList:[{"age":18,"name":"尹正傑"},{"age":19,"name":"yinzhengjie"},{"age":20,"name":"YINZHENGJIE"}] 48 =============我是分割線============= 49 尹正傑 50 yinzhengjie 51 */
三.小試牛刀
是不是覺得json處理其實蠻簡單的,不是嗎?接下來我們來練習以下,解析以下的字串:需要解析商家評論資料:
{"reviewPics":null,"extInfoList":[{"title":"contentTags","values":["環境優雅","價效比高","乾淨衛生","停車方便","音響效果好"],"desc":"","defineType":0},{"title":"tagIds","values":["24","300","852","506","173"],"desc":"","defineType":0}],"expenseList":null,"reviewIndexes":[2],"scoreList":null}
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 import com.alibaba.fastjson.JSON; 9 import com.alibaba.fastjson.JSONArray; 10 import com.alibaba.fastjson.JSONObject; 11 12 import java.util.ArrayList; 13 import java.util.List; 14 15 public class JsonOperation { 16 17 18 public static void main(String[] args) throws Exception { 19 String comment = "{\"reviewPics\":null,\"extInfoList\":[{\"title\":\"contentTags\",\"values\":[\"環境優雅\",\"價效比高\",\"乾淨衛生\",\"停車方便\",\"音響效果好\"],\"desc\":\"\",\"defineType\":0},{\"title\":\"tagIds\",\"values\":[\"24\",\"300\",\"852\",\"506\",\"173\"],\"desc\":\"\",\"defineType\":0}],\"expenseList\":null,\"reviewIndexes\":[2],\"scoreList\":null}"; 20 List<String> taggen = taggen(comment); 21 for (String s : taggen) { 22 System.out.println(s); 23 } 24 25 } 26 /** 27 * 解析商家評論資料 28 */ 29 public static List<String> taggen(String comment){ 30 JSONObject jo = JSON.parseObject(comment); 31 JSONArray jArray = jo.getJSONArray("extInfoList"); 32 if(jArray != null && jArray.size() != 0){ 33 List<String> list = new ArrayList<String>(); 34 //通過jArray得到第一個json串,作為json物件 35 JSONObject jo2 = jArray.getJSONObject(0); 36 JSONArray jArray2 = jo2.getJSONArray("values"); 37 if(jArray2 != null && jArray2.size() != 0){ 38 for (Object o : jArray2) { 39 //System.out.println(o.toString()); 40 list.add(o.toString()); 41 } 42 return list; 43 } 44 } 45 return null; 46 } 47 } 48 49 /* 50 以上程式碼執行結果如下: 51 環境優雅 52 價效比高 53 乾淨衛生 54 停車方便 55 音響效果好 56 */
”