为什么要自己撸一个json格式化的代码?
很多时候json是一个长长的字符串,分析其结构很不爽,更让人不爽的是,你正在使用的环境不允许使用外网。这就比较尴尬了,找个notepad++自己一个一个单词进行格式化。作为一个程序员为什么不学会偷懒呢?自己撸一个json串格式化的code岂不是一劳永逸。
所以,你的条件不满足以上情况的时候,你就没有必要自己撸这样的代码了。不需要对json串进行格式化,你撸它干嘛呢?我有网,我还撸它干嘛呢?
自己怎么撸一个json格式化的代码?
撸代码之前还需理清思路。思路:遇到'{'的时候,后面的内容要换行并且要增加缩进;遇到','的时候,后面的内容直接换行继续上一次的缩进即可;遇到'}'的时候,立马需要换行,换行之前需要减少缩进;遇到其他字符不做处理,你的json需要个性化除外。
奉献代码以及测试结果
工具类代码
package per.util;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JsonUtil {
/**
* 按行读取文件内容
* @param path
* @return
*/
public static String readFile(String path) {
StringBuffer result = new StringBuffer();
BufferedReader br = null;
try {
FileReader fr = new FileReader(path);
br = new BufferedReader(fr);
String line;
int index = 0;
while((line = br.readLine()) != null && index<100) {
result.append(line);
result.append("\n");
System.out.println(line);
index++;
}
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException : " + path);
e.printStackTrace();
} catch (IOException e) {
System.err.println("FileReadException");
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
/**
* 对json字符串进行格式化
* @param source
* @return
*/
public static String string2json(String source) {
StringBuffer result = new StringBuffer();
char[] array = source.toCharArray();
String indent = ""; //缩进
for(int i = 0; i < array.length; i++) {
if('{' == array[i]) {
result.append(array[i]);
indent = indent + " "; //增加两个空格的缩进
result.append("\n");
result.append(indent);
} else if(',' == array[i]){
result.append(array[i]);
result.append("\n");
result.append(indent);
} else if('}' == array[i]) {
//减少两个空格的缩进
indent = indent.substring(0, indent.length()-2);
result.append("\n");
result.append(indent);
result.append(array[i]);
} else {
result.append(array[i]);
}
}
return result.toString();
}
}
测试代码
package per.util.test;
import per.util.JsonUtil;
public class JsonUtilTest {
public static void main(String[] args) {
String path = "E:/config/jsonTest.txt";
String source = JsonUtil.readFile(path);
String result = JsonUtil.string2json(source);
System.out.println(result);
}
}
测试结果
{"reply":{"result":[{"name":"hello","desire":1,"desic":"deployment"},{"name":"word","desire":2,"desic":null}]}}
{
"reply":{
"result":[{
"name":"hello",
"desire":1,
"desic":"deployment"
},
{
"name":"word",
"desire":2,
"desic":null
}]
}
}