首页 > 代码库 > FastJson使用示例

FastJson使用示例

一,几个基本概念

①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使用示例