您的当前位置:首页正文

JSON与文件互转

2024-11-23 来源:个人技术集锦

JSON转文件

createJsonFile

package util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

/**
 * Created on 2018/6/21.
 *
 * @desc JSON转file
 */
public class JsonToFile {
    /**
     * JSON文件
     *
     * @param jsonString JSON字符串
     * @param filePath   文件路径
     * @param fileName   文件名
     * @return JSON文件
     */
    public static boolean createJsonFile(String jsonString, String filePath, String fileName) {
        // 文件生成否
        boolean flag = true;
        // 拼接文件完整路径
        String fullPath = filePath + File.separator;
        // 生JSON文件
        try {
            // 创新文件
            File file = new File(fullPath, fileName);
            if (!file.getParentFile().exists()) {
                // 父目录不存则创父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) {
                // 已存删旧文件
                file.delete();
            }
            file.createNewFile();
            // 格式化JSON字符串
            jsonString = JsonFormat.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;
    }
}
复制代码

JsonFormat

package util;

/**
 * Created on 2018/6/21.
 *
 * @desc JSON格式化
 */
public class JsonFormat {
    /**
     * 格式化JSON字符串
     *
     * @param json 未格式化JSON字符串
     * @return 格式化JSON字符串
     */
    public static String formatJson(String json) {
        StringBuilder result = new StringBuilder();
        int length = json.length();
        int number = 0;
        char key;
        // 遍历输入字符串
        for (int i = 0; i < length; i++) {
            // 一【当前字符】
            key = json.charAt(i);
            // 二【当前字符前是括号/花括号】
            if ((key == '[') || (key == '{')) {
                // (1)前仍有字符且“:”,打印换行缩进
                if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
                    result.append('\n');
                    result.append(indent(number));
                }
                // (2)打印当前字符
                result.append(key);
                // (3)前方括号/花括号则后换行
                result.append('\n');
                // (4)每现一次前方括号/花括号,缩进次数增一
                number++;
                result.append(indent(number));
                // (5)下次循环
                continue;
            }
            // 三【当前字符后方括号/花括号】
            if ((key == ']') || (key == '}')) {
                // (1)后方括号/花括号则前换行
                result.append('\n');
                // (2)每现一次后方括号/花括号,缩进次数减一
                number--;
                result.append(indent(number));
                // (3)打印当前字符
                result.append(key);
                // (4)当前字符后还有字符且不为“,”
                if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
                    result.append('\n');
                }
                // (5)下次循环
                continue;
            }
            // 四【当前字符逗号,逗号后换行缩进,不改缩进次数】
            if ((key == ',')) {
                result.append(key);
                result.append('\n');
                result.append(indent(number));
                continue;
            }
            // 五【打印当前字符】
            result.append(key);
        }
        return result.toString();
    }

    /**
     * 返指定次数的缩进字符串(每次缩三空格,即SPACE)
     *
     * @param number 缩进次数
     * @return 指定缩进次数的字符串
     */
    private static String indent(int number) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < number; i++) {
            String space = "   ";
            result.append(space);
        }
        return result.toString();
    }
}
复制代码

主代码

JsonToFile.createJsonFile(JsonFormat.formatJson(response), getContext().getExternalFilesDir("DfsDataSync").getAbsolutePath(), "ProjectDepartmentTeamNumberWellNumber.json");
App.azCache().put(Flag.PROJECT_DEPARTMENT_TEAM_NUMBER_WELL_NUMBER_FILE_PATH, getContext().getExternalFilesDir("DfsDataSync").getAbsolutePath() + File.separator + "ProjectDepartmentTeamNumberWellNumber.json");
复制代码

文件转JSON

JsonTransform

package util;

import android.content.Context;
import android.content.res.AssetManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created on 2018/4/3.
 *
 * @author xxx
 * @desc JSON转化
 */
public class JsonTransform {
    /**
     * 文件转JSON
     *
     * @param filePath 文件路径
     * @return JSON
     */
    public static String jsonTransformFromFile(String filePath) {
        File file = new File(filePath);
        StringBuilder stringBuilder = new StringBuilder();
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            BufferedReader bf = new BufferedReader(new InputStreamReader(fileInputStream));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * assets转JSON
     *
     * @param context    上下文
     * @param assetsPath assets路径
     * @return JSON
     */
    public String jsonTransformFromAssets(Context context, String assetsPath) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(assetsPath)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
复制代码

主代码一(三级联动)

package data;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import util.JsonParse;
import util.JsonTransform;

/**
 * Created on 2018/6/26.
 *
 * @desc 项目部/对号/井号联动
 * {
 * "第五项目部": {
 * "40527": [
 * "苏6-8-23",
 * "苏6-8-25H1"
 * ]
 * }
 * "第一项目部": {
 * "30109": [
 * "白加218-341",
 * "郭6-03j"
 * ]
 * }
 * }
 */
public class ProDepTnWnLinkage {
    /**
     * 项目部
     *
     * @param filePath 文件路径
     * @return 项目部
     */
    public static List<String> projectDepartment(String filePath) {
        List<String> list = new ArrayList<>();
        String jsonString = JsonTransform.jsonTransformFromFile(filePath);
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            Iterator iterator = jsonObject.keys();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                list.add(key);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 据项目部获队号
     *
     * @param filePath          文件路径
     * @param projectDepartment 项目部
     * @return 队号
     */
    public static List<String> teamNumberBaseOnProjectDepartment(String filePath, String projectDepartment) {
        List<String> list = new ArrayList<>();
        String jsonString = JsonTransform.jsonTransformFromFile(filePath);
        try {
            // 项目部
            JSONObject projectDepartmentJsonObject = new JSONObject(jsonString);
            Iterator projectDepartmentIterator = projectDepartmentJsonObject.keys();
            while (projectDepartmentIterator.hasNext()) {
                String projectDepartmentKey = (String) projectDepartmentIterator.next();
                if (projectDepartment != null && !"".equals(projectDepartment) && projectDepartmentKey.equals(projectDepartment)) {
                    // 队号
                    JSONObject teamNumberJsonObject = (JSONObject) projectDepartmentJsonObject.get(projectDepartmentKey);
                    Iterator teamNumberIterator = teamNumberJsonObject.keys();
                    while (teamNumberIterator.hasNext()) {
                        String teamNumberKey = (String) teamNumberIterator.next();
                        list.add(teamNumberKey);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 据项目部对号获井号
     *
     * @param filePath          文件路径
     * @param projectDepartment 项目部
     * @param teamNumber        对号
     * @return 井号
     */
    public static List<String> wellNumberBaseOnProjectDepartmentTeamNumber(String filePath, String projectDepartment, String teamNumber) {
        List<String> list = new ArrayList<>();
        String jsonString = JsonTransform.jsonTransformFromFile(filePath);
        try {
            // 项目部
            JSONObject projectDepartmentJsonObject = new JSONObject(jsonString);
            Iterator projectDepartmentIterator = projectDepartmentJsonObject.keys();
            while (projectDepartmentIterator.hasNext()) {
                String projectDepartmentKey = (String) projectDepartmentIterator.next();
                if (projectDepartment != null && !"".equals(projectDepartment) && projectDepartmentKey.equals(projectDepartment)) {
                    // 队号
                    JSONObject teamNumberJsonObject = (JSONObject) projectDepartmentJsonObject.get(projectDepartmentKey);
                    Iterator teamNumberIterator = teamNumberJsonObject.keys();
                    while (teamNumberIterator.hasNext()) {
                        String teamNumberKey = (String) teamNumberIterator.next();
                        if (teamNumber != null && !"".equals(teamNumber) && teamNumber.equals(teamNumberKey)) {
                            // 井号
                            Object wellNumberObject = teamNumberJsonObject.get(teamNumberKey);
                            JsonArray jsonArray = JsonParse.noHeaderArrayParse(wellNumberObject.toString());
                            for (JsonElement jsonElement : jsonArray) {
                                list.add(jsonElement.toString());
                            }
                        }
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}
复制代码

主代码二(两级联动)

package data;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import util.JsonParse;
import util.JsonTransform;

/**
 * Created on 2018/6/27.
 *
 * @desc 施工类型/井型联动
 * {
 * "常规水平井": [
 * "三开水平井",
 * "二开水平井",
 * "大位移定向井"
 * ],
 * "常规井": [
 * "二开水平井",
 * "定向井",
 * "定向气井",
 * "直井"
 * ]
 * }
 */
public class ConstructionTypeWellTypeLinkage {
    /**
     * 施工类型
     *
     * @param filePath 文件路径
     * @return 施工类型
     */
    public static List<String> constructionType(String filePath) {
        List<String> list = new ArrayList<>();
        String jsonString = JsonTransform.jsonTransformFromFile(filePath);
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            Iterator iterator = jsonObject.keys();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                list.add(key);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 井型
     *
     * @param filePath 文件路径
     * @return 井型
     */
    public static List<String> wellTypeBaseOnConstructionType(String filePath, String constructionType) {
        List<String> list = new ArrayList<>();
        String jsonString = JsonTransform.jsonTransformFromFile(filePath);
        try {
            // 施工类型
            JSONObject constructionTypeJsonObject = new JSONObject(jsonString);
            Iterator iterator = constructionTypeJsonObject.keys();
            while (iterator.hasNext()) {
                String constructionTypeKey = (String) iterator.next();
                if (constructionType != null && !"".equals(constructionType) && constructionType.equals(constructionTypeKey)) {
                    // 井型
                    Object wellTypeObject = constructionTypeJsonObject.get(constructionTypeKey);
                    JsonArray jsonArray = JsonParse.noHeaderArrayParse(wellTypeObject.toString());
                    for (JsonElement jsonElement : jsonArray) {
                        list.add(jsonElement.toString());
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}
复制代码
显示全文