Java SpringBoot对JSON格式化存储

package com.example.automatedtrading.util;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class JsonStrong {
    public static void main(String[] args) throws IOException {
        writeJson();
        JSONObject jsonObject = readJson();
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("contractsPool").toString());
        JSONObject parseObject = JSONObject.parseObject(jsonArray.get(0).toString());
        System.out.println(parseObject.get("key"));
    }

    public static JSONObject readJson() throws IOException {
        String path = System.getProperty("user.dir")+"/json";
        File file = new File(path+"/"+"test.json");
        FileReader reader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String str;
        StringBuilder stringBuilder= new StringBuilder();
        while ((str = bufferedReader.readLine())!=null){
            System.out.println(str);
            stringBuilder.append(str);
        }
        bufferedReader.close();
        reader.close();
        return JSONObject.parseObject(stringBuilder.toString());
    }

    public static void writeJson() throws IOException {
        Map<String,Object> map = new JSONObject();
        map.put("dominantContract","SA208");
        map.put("direction",3);
        map.put("contractsPool","[{\"key\":1,\"edit\":false,\"contractName\":\"SA207\",\"buyOpen1\":1,\"sellFlat1\":-1,\"sellOpen1\":-1,\"buyFlat1\":-1,\"buyOpen2\":-1,\"sellFlat2\":-1,\"sellOpen2\":-1,\"buyFlat2\":-1,\"ratio\":-1}]");
        map.put("orderNumber",1);
        String json = formatJson(JSONObject.parseObject(map.toString()).toJSONString());
        String path = System.getProperty("user.dir")+"/json";
        File fileJson = new File(path);
        if (!fileJson.exists()){
            System.out.println("successful?"+fileJson.mkdirs());
        }
        File file = new File(path+"/"+"test.json");
        FileWriter writer = new FileWriter(file);
        writer.write(json);
        writer.write("\n");
        writer.close();
    }

    /**
     * 格式化
     *
     */
    public static String formatJson(String jsonStr) {
        if (null == jsonStr || "".equals(jsonStr)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        char last;
        char current = '\0';
        int indent = 0;
        boolean isInQuotationMarks = false;
        for (int i = 0; i < jsonStr.length(); i++) {
            last = current;
            current = jsonStr.charAt(i);
            switch (current) {
                case '"':
                    if (last != '\\'){
                        isInQuotationMarks = !isInQuotationMarks;
                    }
                    sb.append(current);
                    break;
                case '{':
                case '[':
                    sb.append(current);
                    if (!isInQuotationMarks) {
                        sb.append('\n');
                        indent++;
                        addIndentBlank(sb, indent);
                    }
                    break;
                case '}':
                case ']':
                    if (!isInQuotationMarks) {
                        sb.append('\n');
                        indent--;
                        addIndentBlank(sb, indent);
                    }
                    sb.append(current);
                    break;
                case ',':
                    sb.append(current);
                    if (last != '\\' && !isInQuotationMarks) {
                        sb.append('\n');
                        addIndentBlank(sb, indent);
                    }
                    break;
                default:
                    sb.append(current);
            }
        }

        return sb.toString();
    }

    /**
     * 添加space
     */
    private static void addIndentBlank(StringBuilder sb, int indent) {
        for (int i = 0; i < indent; i++) {
            sb.append('\t');
        }
    }
}

 控制台输出:

{
	"contractsPool":"[{\"key\":1,\"edit\":false,\"contractName\":\"SA207\",\"buyOpen1\":1,\"sellFlat1\":-1,\"sellOpen1\":-1,\"buyFlat1\":-1,\"buyOpen2\":-1,\"sellFlat2\":-1,\"sellOpen2\":-1,\"buyFlat2\":-1,\"ratio\":-1}]",
	"orderNumber":1,
	"dominantContract":"SA208",
	"direction":3
}
1

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值