zoukankan      html  css  js  c++  java
  • json文件常用代码

    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('
    ');
    32                     result.append(indent(number));
    33                 }
    34 
    35                 // (2)打印:当前字符。
    36                 result.append(key);
    37 
    38                 // (3)前方括号、前花括号,的后面必须换行。打印:换行。
    39                 result.append('
    ');
    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('
    ');
    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('
    ');
    64                 }
    65 
    66                 // (5)继续下一次循环。
    67                 continue;
    68             }
    69 
    70             // 4、如果当前字符是逗号。逗号后面换行,并缩进,不改变缩进次数。
    71             if ((key == ',')) {
    72                 result.append(key);
    73                 result.append('
    ');
    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
  • 相关阅读:
    No-3.Linux 终端命令格式
    No-2.常用 Linux 命令的基本使用
    No-1.文件和目录
    No-7.运算符
    No-6.If语句
    No-5.变量的命名
    YOLOv4详细分析 | 细数当前最佳检测框架小细节(附论文及源码下载)
    案例】S7-200SMART 实时时钟如何在MCGS触摸屏上显示并写入
    卡尔曼滤波:从入门到精通
    mmdetection最小复刻版(七):anchor-base和anchor-free差异分析
  • 原文地址:https://www.cnblogs.com/lihuibin/p/10259370.html
Copyright © 2011-2022 走看看