ccf json解析 java,java格式化json串

闲来无事,写一段代码,格式json字符串,不是解析奥,只是让json看起来更规整一些。

package com.sortworld;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.util.Stack;

public class JsonFormat {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(

new FileReader(new File("E://h")));

String jsons = "", str;

while ((str = br.readLine()) != null) {

jsons += str;

}

br.close();

System.out.println(format(jsons, 0));

}

private static Stack stack = new Stack();

public static String format(String json, int depth) {

String result = "";

for (int i = 0; i < json.length(); i++) {

char c = json.charAt(i);

if (c == '[')

stack.push(i);

if (c == ']') {

int popTag = stack.pop();

if (stack.isEmpty()) {

String childJson = json.substring(popTag + 1, i);

// 递归解析数组

result += "[" + format(childJson, depth + 2)

+ tokenStr(depth) + "";

}

}

if (stack.isEmpty()) {

String token = getToken(c, depth, json, i);

result += token;

}

}

return result;

}

//

private static String getToken(char c, int depth, String json, int i) {

if (c == '{' || c == '}')

return "\n" + tokenStr(depth + 1) + c + "\n" + tokenStr(depth + 2);

if (c == ',' && json.charAt(i + 1) == '\"')

return c + "\n" + tokenStr(depth + 2);

if (c == ']')

return "\n" + tokenStr(depth + 2) + c + "\n" + tokenStr(depth + 2);

return c + "";

}

// 分隔符

private static String tokenStr(int depth) {

String token = "";

for (int i = 0; i < depth; i++)

token += " ";

return token;

}

}

测试用例

{"count":1,"distance":0,"result":[{"deadLineTime":"2000-01-01 00:00:00","districtId":14768},{"deadLineTime":"2000-01-01 00:00:00"}],"time":2} 测试结果

{

"count":1,

"distance":0,

"result":[

{

"deadLineTime":"2000-01-01 00:00:00",

"districtId":14768

}

,

{

"deadLineTime":"2000-01-01 00:00:00"

}

]

,

"time":2

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值