⽤JAVA给JSON进⾏排版
之前听到朋友的⾯试题,是如何对JSON进⾏排版,于是就写了⼀个Demo,觉得挺有意思的,就贴出来了。这个就是记录缩进来输出,⼤家也可以尝试⼀下其他更好算法来进⾏输出。
功能:可以把⼀⾏的JSON字符串格式化后进⾏输出,带有缩进,看起来更加直观。
⽀持JSON格式的字符串和⽂件格式化输出。
代码:
package json;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import vote.Vote;
/**
* JSON打印器
* @author jiujie
* @version $Id: JSONPrinter.java, v 0.1 2016年7⽉28⽇下午5:08:41 jiujie Exp $recently的用法
*/
public class JSONPrinter {
chance是什么意思
junsprivate Object jsonObj;
杯子的英文
/**
* JSON⽂件打印器
谢东萤* constructor
* @author jiujie
* 2016年7⽉28⽇下午5:08:59
* @param jsonFile
*/
public JSONPrinter(File jsonFile) {
this.jsonObj = jsonFile;
}
/**
* JSON字符串打印器
* constructor
* @author jiujie
* 2016年7⽉28⽇下午5:08:59
* @param jsonString
*/
public JSONPrinter(String jsonString) {
this.jsonObj = jsonString;
}
public void print() {
if (jsonObj instanceof File) {
try {
print(new FileInputStream((File) jsonObj));
} catch (Exception e) {
e.printStackTrace();
}
} el if (jsonObj instanceof String) {
try {
print(new ByteArrayInputStream(((String) jsonObj).getBytes()));
} catch (Exception e) {
e.printStackTrace();一对一辅导班
}
}
}
private void print(InputStream inputStream) throws IOException {
mirthlessInputStreamReader in = new InputStreamReader(inputStream);
int read = 0;
int indent = 0;
while ((read = in.read()) > 0) {
char ch = (char) read;
switch (ch) {
ca '{': {
indent = printAndRightMove(indent, ch);
break;
}
ca '}': {
indent = printAndLeftMove(indent, ch);
break;
}
ca '[': {
indent = printAndRightMove(indent, ch);
break;
}
ca ']': {
indent = printAndLeftMove(indent, ch);
break;
}
ca ',': {
System.out.println(ch);
System.out.print(getBlankString(indent));
break;
}
default: {
System.out.print(ch);
break;
}
}
}
in.clo();
}
private int printAndLeftMove(int indent, char ch) {
System.out.println();
indent -= 2;
System.out.print(getBlankString(indent) + ch);
return indent;
}
private int printAndRightMove(int indent, char ch) {
System.out.println();
System.out.println(getBlankString(indent) + ch);
indent += 2;
System.out.print(getBlankString(indent));
return indent;
}
private String getBlankString(int length) {
if (length <= 0) {
return "";freeoz
}
String blankString = "";
for (int i = 0; i < length; i++) {
blankString += " ";
}
return blankString;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
ClassLoader classLoader = ClassLoader();
String path = Resource("").toString().replace("/bin", "").replace("file:/", "") + "src/";
JSONPrinter jsonPrinter = new JSONPrinter(new File(path));
jsonPrinter.print();
JSONPrinter stringJsonPrinter = new JSONPrinter("{score:100,age:30}");
stringJsonPrinter.print();
}
}
输出
{
{
"name":"perfumeType",
2013年专八考试时间"values":
[
"EDT",
"EDP"
]
,
"countMap":
{
"EDT":68,
"EDP":27
}
}
]
}
{
score:100, age:30
覆盖英语}