1. 程式人生 > >json文件常用代碼

json文件常用代碼

pla pub 發生 amp sed 逗號 img num 並且

1、json數據內容格式化處理

技術分享圖片
 1 package com.sklm.lhb.json;
 2 
 3 public class JsonFormatTool {
 4 
 5     /**
 6      * 單位縮進字符串。
 7      */
 8     private static String SPACE = "   ";
 9 
10     /**
11      * 返回格式化JSON字符串。
12      * 
13      * @param json 未格式化的JSON字符串。
14      * @return 格式化的JSON字符串。
15      */
16     public
static String formatJson(String json) { 17 StringBuffer result = new StringBuffer(); 18 int length = json.length(); 19 int number = 0; 20 char key = 0; 21 22 // 遍歷輸入字符串。 23 for (int i = 0; i < length; i++) { 24 // 1、獲取當前字符。 25 key = json.charAt(i);
26 27 // 2、如果當前字符是前方括號、前花括號做如下處理: 28 if ((key == ‘[‘) || (key == ‘{‘)) { 29 // (1)如果前面還有字符,並且字符為“:”,打印:換行和縮進字符字符串。 30 if ((i - 1 > 0) && (json.charAt(i - 1) == ‘:‘)) { 31 result.append(‘\n‘); 32 result.append(indent(number));
33 } 34 35 // (2)打印:當前字符。 36 result.append(key); 37 38 // (3)前方括號、前花括號,的後面必須換行。打印:換行。 39 result.append(‘\n‘); 40 41 // (4)每出現一次前方括號、前花括號;縮進次數增加一次。打印:新行縮進。 42 number++; 43 result.append(indent(number)); 44 45 // (5)進行下一次循環。 46 continue; 47 } 48 49 // 3、如果當前字符是後方括號、後花括號做如下處理: 50 if ((key == ‘]‘) || (key == ‘}‘)) { 51 // (1)後方括號、後花括號,的前面必須換行。打印:換行。 52 result.append(‘\n‘); 53 54 // (2)每出現一次後方括號、後花括號;縮進次數減少一次。打印:縮進。 55 number--; 56 result.append(indent(number)); 57 58 // (3)打印:當前字符。 59 result.append(key); 60 61 // (4)如果當前字符後面還有字符,並且字符不為“,”,打印:換行。 62 if (((i + 1) < length) && (json.charAt(i + 1) != ‘,‘)) { 63 result.append(‘\n‘); 64 } 65 66 // (5)繼續下一次循環。 67 continue; 68 } 69 70 // 4、如果當前字符是逗號。逗號後面換行,並縮進,不改變縮進次數。 71 if ((key == ‘,‘)) { 72 result.append(key); 73 result.append(‘\n‘); 74 result.append(indent(number)); 75 continue; 76 } 77 78 // 5、打印:當前字符。 79 result.append(key); 80 } 81 82 return result.toString(); 83 } 84 85 /** 86 * 返回指定次數的縮進字符串。每一次縮進三個空格,即SPACE。 87 * 88 * @param number 縮進次數。 89 * @return 指定縮進次數的字符串。 90 */ 91 private static String indent(int number) { 92 StringBuffer result = new StringBuffer(); 93 for (int i = 0; i < number; i++) { 94 result.append(SPACE); 95 } 96 return result.toString(); 97 } 98 }
JsonFormatTool

2、json數據內容的創建和讀取

技術分享圖片
 1 package com.sklm.lhb.json;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.FileReader;
 6 import java.io.OutputStreamWriter;
 7 import java.io.Writer;
 8 import org.json.simple.JSONArray;
 9 import org.json.simple.JSONObject;
10 import org.json.simple.parser.JSONParser;
11 
12 public class JsonFileUtil {
13 
14     /**
15      * 生成.json格式文件
16      * @param jsonString    json內容
17      * @param filePath      文件路徑
18      * @param fileName      json文件名稱
19      * @return  如果文件創建成功返回true,否則返回false
20      */
21     public static boolean createJsonFile(String jsonString, String filePath, String fileName) {
22         boolean flag = true;
23         String fullPath = filePath +File.separator+ fileName + ".json";
24          try {
25             File file = new File(fullPath);
26             if(!file.getParentFile().exists()) {
27                 file.getParentFile().mkdirs();
28             }
29             if(file.exists()) {
30                 file.delete();
31                 file.createNewFile();
32             }else {
33                 file.createNewFile();
34             }
35             
36             //格式化json字符串
37             jsonString = JsonFormatTool.formatJson(jsonString);
38             
39             Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
40             write.write(jsonString);
41             write.flush();
42             write.close();
43             
44         } catch (Exception e) {
45             flag = false;
46             e.printStackTrace();
47         }
48         
49         return flag;
50     }
51     
52     /**
53      * 讀取json文件
54      * @param jsonPath    文件路徑
55      * @param jsonName    文件名稱
56      * @return 返回JSONArray,如果發生 異常則返回null
57      */
58     public static JSONArray readJsonToArray(String jsonPath, String jsonName) {
59         String path = jsonPath+"\\"+jsonName+".json";
60         try {
61             JSONParser parse = new JSONParser();
62             File jsonFile = new File(path);
63             if(!jsonFile.exists()) {
64                 JsonFileUtil.createJsonFile("[]", jsonPath, jsonName);
65             }
66             JSONArray jsonArray = (JSONArray) parse.parse(new FileReader(jsonFile));
67             return jsonArray;
68         } catch (Exception e) {
69             e.printStackTrace();
70         }
71         return null;
72     }
73     
74     /**
75      * 讀取json文件
76      * @param jsonPath    文件路徑
77      * @param jsonName    文件名稱
78      * @return  返回JSONObject,如果發生 異常則返回null
79      */
80     public static JSONObject readJsonToObject(String jsonPath, String jsonName) {
81         String path = jsonPath+"\\"+jsonName+".json";
82         try {
83             JSONParser parse = new JSONParser();
84             File jsonFile = new File(path);
85             if(!jsonFile.exists()) {
86                 JsonFileUtil.createJsonFile("[]", path, jsonName);
87             }
88             JSONObject jsonObject = (JSONObject) parse.parse(new FileReader(jsonFile));
89             return jsonObject;
90         } catch (Exception e) {
91             e.printStackTrace();
92         }
93         return null;    
94     }
95 }
JsonFileUtil

json文件常用代碼