1. 程式人生 > >FastJson使用示例

FastJson使用示例

obj iba json格式數據 對象 value ati logs java nal

一,幾個基本概念

①JSONArray 相當於 JAVA中的List<Object>,如:[‘a‘,‘b‘,‘c‘....]

②JSONObject相當於JAVA中的Map<String, Object>,如:{‘1‘:‘a‘, ‘2‘:‘b‘...}

③對於具有結構層次的JSON格式的數據,可以一層一層地來解析,可參考:這篇文章

二,當待解析的JSON文件很大時,可使用JSON Stream API,比如如下 List類型的數據在 F:\\test.txt 中,假設有上萬條時...:

[
{"begin_int":"1677721","end_int":"1677747"},
{"begin_int":"1677747","end_int":"1677823"},
{"begin_int":"1677824","end_int":"1677926"},
{"begin_int":"1677926","end_int":"1678131"},
{"begin_int":"1678131","end_int":"1678540"},
{"begin_int":"1678540","end_int":"1679359"},
{"begin_int":"1690880","end_int":"1690905"},
{"begin_int":"1690905","end_int":"1690931"},
{"begin_int":"1690931","end_int":"1690956"},
{"begin_int":"1690956","end_int":"1690982"}
]

解析代碼:將List中的每個元素當作一個Object

 1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.FileReader;
 4 
 5 import com.alibaba.fastjson.JSONReader;
 6 
 7 public class ParseListByFastJsonStreamApi {
 8 
 9     private static final String FILE_PATH = "F:\\test.txt";
10     
11
public static void main(String[] args) throws FileNotFoundException{ 12 13 JSONReader jsonReader = new JSONReader(new FileReader(new File(FILE_PATH))); 14 15 jsonReader.startArray();//---> [ 16 17 while(jsonReader.hasNext()) 18 { 19 String info = jsonReader.readObject().toString();//
---> {"key":"value"} 20 System.out.println(info); 21 } 22 jsonReader.endArray();//---> ] 23 jsonReader.close(); 24 } 25 }

或者用如下代碼來解析:(將List中的每個元素(如: {"begin_int":"1690956","end_int":"1690982"})再進一步分解 成 Key 和 Value 對)

 1     public static void parse() throws FileNotFoundException{
 2             
 3             JSONReader jsonReader = new JSONReader(new FileReader(new File(FILE_PATH)));
 4             
 5             jsonReader.startArray();//---> [
 6             
 7             while(jsonReader.hasNext())
 8             {
 9                 jsonReader.startObject();
10                 while(jsonReader.hasNext()) {
11                     String objKey = jsonReader.readString();
12                     String objVal = jsonReader.readObject().toString();
13                     System.out.println("key: " + objKey + ", value: " + objVal);
14                 }
15                 jsonReader.endObject();
16             }
17             jsonReader.endArray();//---> ]
18             jsonReader.close();
19     }

上面的第9行 和 第10行解析代碼也驗證了:“JSONObject相當於JAVA中的Map<String, Object>”。

或者根據 JAVA Bean 類來解析:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import com.alibaba.fastjson.JSONReader;

public class ParseListByFastJsonStreamApi {

    private static final String FILE_PATH = "F:\\test.txt";
    
    public static void main(String[] args) throws FileNotFoundException{
        
        JSONReader jsonReader = new JSONReader(new FileReader(new File(FILE_PATH)));
        
        jsonReader.startArray();//---> [
        
        while(jsonReader.hasNext())
        {
            BeginEndBean obj = jsonReader.readObject(BeginEndBean.class);//根據 java bean 來解析
            int begin_int = obj.getBegin_int();
            int end_int = obj.getEnd_int();
            System.out.println("begin_int:" + begin_int + ", end_int" + end_int); 
        }
        jsonReader.endArray();//---> ]
        jsonReader.close();
    }
}

JAVA Bean類如下:

 1 public class BeginEndBean {
 2     private int begin_int;
 3     private int end_int;
 4     public int getBegin_int() {
 5         return begin_int;
 6     }
 7     public void setBegin_int(int begin_int) {
 8         this.begin_int = begin_int;
 9     }
10     public int getEnd_int() {
11         return end_int;
12     }
13     public void setEnd_int(int end_int) {
14         this.end_int = end_int;
15     }
16 }

三,當需要解析JSON數據格式有點復雜(非扁平的數據)時,比如下面的JSON格式數據:

{"key":"value","anotherKey":[
{"begin_int":"1677721","end_int":"1677747"},
{"begin_int":"1687552","end_int":"1690828"},
{"begin_int":"1690905","end_int":"1690931"},
{"begin_int":"1690931","end_int":"1690956"},
{"begin_int":"1690956","end_int":"1690982"}
],"thirdKey":{"subKey":"subVal","anotherSubKey":["1","2","3"]}}

"key" 對應的就是只有一個值,"anotherKey"對應的是一個列表,"thirdKey"對應的是一個對象(Map)。

解析代碼如下:

第17行,將整個Json格式的文件當作一個JSONObject,該JSONObject裏面有三個子元素,分別是:"key" 、"anotherKey"、"thirdKey"。因此第18行 while(hasNext())找到每個key,然後 if-else 分別解析對應的值。比如第25行,解析到"anotherKey"時,它對應的是一個List,因此在第26行 startArray() 來讀取

由於List中的每個元素其實又是一個個的:{"begin_int":"1687552","end_int":"1690828"}

因此,第29行又開啟 startObject() 讀取,而每個{"begin_int":"1687552","end_int":"1690828"} 又有兩個 ”xxx_int“:"xxx",因此第30行又有一個while(hasNext())循環。

總之,讀取Map格式的數據對應的是JSONObject,讀取的方法就是 jsonReader.readObject()

 1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.FileReader;
 4 import com.alibaba.fastjson.JSONReader;
 5 
 6 public class ParseListByFastJsonStreamApi {
 7 
 8     private static final String FILE_PATH = "F:\\test.txt";
 9 
10     public static void main(String[] args) throws FileNotFoundException {
11         parseData();
12     }
13 
14     public static void parseData() throws FileNotFoundException {
15         JSONReader jsonReader = new JSONReader(new FileReader(new File(FILE_PATH)));
16         
17         jsonReader.startObject();//將整個json文件當作 Map<String,Object> 對象來解析 {,}
18         while(jsonReader.hasNext()) {
19             String key = jsonReader.readString();
20             if(key.equals("key"))//"key"對應的Object只有一個
21             {
22                 Object obj = jsonReader.readObject();//
23                 String val = obj.toString();
24                 System.out.println("obj: " + obj + ", value: " + val);
25             }else if(key.equals("anotherKey")) {//"anotherKey"對應的是一個List對象
26                 jsonReader.startArray();//---> [  開啟讀List對象
27                 while(jsonReader.hasNext()) {
28                     
29                     jsonReader.startObject();
30                     while(jsonReader.hasNext()) {
31                         String objKey = jsonReader.readString();
32                         String objVal = jsonReader.readObject().toString();
33                         System.out.println("objKey: " + objKey + ", objVal: " + objVal);
34                     }
35                     jsonReader.endObject();
36                 }
37                 jsonReader.endArray();//---> ]
38             }else if(key.equals("thirdKey")) {
39                 jsonReader.startObject();//{"subKey":"subVal","anotherSubKey":["1","2","3"]}
40                 while(jsonReader.hasNext()) {
41                     String sub_key = jsonReader.readString();
42                     Object third_obj = jsonReader.readObject();
43                     String subVal = third_obj.toString();
44                     System.out.println("sub_key: " + sub_key + ", subVal: " + subVal);
45                 }
46                 jsonReader.endObject();
47             }
48         }
49         jsonReader.endObject();
50         jsonReader.close();
51     }
52 }

也可以借助JAVA Bean 來解析 anotherKey 對應的 List 對象。代碼如下:

技術分享
 1 public class ParseListByFastJsonStreamApi {
 2 
 3     private static final String FILE_PATH = "F:\\test.txt";
 4 
 5     public static void main(String[] args) throws FileNotFoundException {
 6         parseData();
 7     }
 8 
 9     public static void parseData() throws FileNotFoundException {
10         JSONReader jsonReader = new JSONReader(new FileReader(new File(FILE_PATH)));
11         
12         jsonReader.startObject();//將整個json文件當作 Map<String,Object> 對象來解析 {,}
13         while(jsonReader.hasNext()) {
14             String key = jsonReader.readString();
15             if(key.equals("key"))//"key"對應的Object只有一個
16             {
17                 Object obj = jsonReader.readObject();//
18                 String val = obj.toString();
19                 System.out.println("obj: " + obj + ", value: " + val);
20             }else if(key.equals("anotherKey")) {//"anotherKey"對應的是一個List對象
21                 jsonReader.startArray();//---> [  開啟讀List對象
22                 while(jsonReader.hasNext()) {
23                     BeginEndBean objBean = jsonReader.readObject(BeginEndBean.class);
24                     int begin_int = objBean.getBegin_int();
25                     int end_int = objBean.getEnd_int();
26                     System.out.println("begin_int: " + begin_int + ", " + end_int);
27                 }
28                 jsonReader.endArray();//---> ]
29             }else if(key.equals("thirdKey")) {
30                 jsonReader.startObject();//{"subKey":"subVal","anotherSubKey":["1","2","3"]}
31                 while(jsonReader.hasNext()) {
32                     String sub_key = jsonReader.readString();
33                     Object third_obj = jsonReader.readObject();
34                     String subVal = third_obj.toString();
35                     System.out.println("sub_key: " + sub_key + ", subVal: " + subVal);
36                 }
37                 jsonReader.endObject();
38             }
39         }
40         jsonReader.endObject();
41         jsonReader.close();
42     }
43 }
View Code

兩種方法的對比如下:

 1 else if(key.equals("anotherKey")) {//"anotherKey"對應的是一個List對象
 2                 jsonReader.startArray();//---> [  開啟讀List對象
 3                 while(jsonReader.hasNext()) {
 4                     BeginEndBean objBean = jsonReader.readObject(BeginEndBean.class);
 5                     int begin_int = objBean.getBegin_int();
 6                     int end_int = objBean.getEnd_int();
 7                     System.out.println("begin_int: " + begin_int + ", " + end_int);
 8                 }
 9                 jsonReader.endArray();//---> ]
10             }
11 
12 
13 ---------------------------------------------------------------------------
14 
15 else if(key.equals("anotherKey")) {//"anotherKey"對應的是一個List對象
16                 jsonReader.startArray();//---> [  開啟讀List對象
17                 while(jsonReader.hasNext()) {
18                     jsonReader.startObject();
19                     while(jsonReader.hasNext()) {
20                         String objKey = jsonReader.readString();
21                         String objVal = jsonReader.readObject().toString();
22                         System.out.println("objKey: " + objKey + ", objVal: " + objVal);
23                     }
24                     jsonReader.endObject();
25                 }
26                 jsonReader.endArray();//---> ]
27             }

FastJson 官方github資料

FastJson使用示例