javaはjsonフォーマットファイルの例コードをエクスポートします。


本論文では、JavaがJson形式のファイルをエクスポートするための例示的なコードを紹介します。
jsonファイルコードを生成:

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

public class CreateFileUtil {

  /**
   *   .json    
   */
  public static boolean createJsonFile(String jsonString, String filePath, String fileName) {
    //           
    boolean flag = true;

    //         
    String fullPath = filePath + File.separator + fileName + ".json";

    //   json    
    try {
      //          
      File file = new File(fullPath);
      if (!file.getParentFile().exists()) { //         ,     
        file.getParentFile().mkdirs();
      }
      if (file.exists()) { //      ,     
        file.delete();
      }
      file.createNewFile();

      //    json   
      jsonString = JsonFormatTool.formatJson(jsonString);

      //              
      Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
      write.write(jsonString);
      write.flush();
      write.close();
    } catch (Exception e) {
      flag = false;
      e.printStackTrace();
    }

    //          
    return flag;
  }

}
json文字列フォーマットツールコード:


public class JsonFormatTool {
  /**
   *        。
   */
  private static String SPACE = "  ";

  /**
   *      JSON   。
   * 
   * @param json      JSON   。
   * @return     JSON   。
   */
  public static String formatJson(String json) {
    StringBuffer result = new StringBuffer();

    int length = json.length();
    int number = 0;
    char key = 0;

    //        。
    for (int i = 0; i < length; i++) {
      // 1、      。
      key = json.charAt(i);

      // 2、           、         :
      if ((key == '[') || (key == '{')) {
        // (1)        ,     “:”,  :          。
        if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
          result.append('
'); result.append(indent(number)); } // (2) : 。 result.append(key); // (3) 、 , 。 : 。 result.append('
'); // (4) 、 ; 。 : 。 number++; result.append(indent(number)); // (5) 。 continue; } // 3、 、 : if ((key == ']') || (key == '}')) { // (1) 、 , 。 : 。 result.append('
'); // (2) 、 ; 。 : 。 number--; result.append(indent(number)); // (3) : 。 result.append(key); // (4) , “,”, : 。 if (((i + 1) < length) && (json.charAt(i + 1) != ',')) { result.append('
'); } // (5) 。 continue; } // 4、 。 , , 。 if ((key == ',')) { result.append(key); result.append('
'); result.append(indent(number)); continue; } // 5、 : 。 result.append(key); } return result.toString(); } /** * 。 , SPACE。 * * @param number 。 * @return 。 */ private static String indent(int number) { StringBuffer result = new StringBuffer(); for (int i = 0; i < number; i++) { result.append(SPACE); } return result.toString(); } }
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。