java输出排版_用JAVA给JSON进行排版

packagejson;importjava.io.ByteArrayInputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importvote.Vote;/*** JSON打印器

*@authorjiujie

*@version$Id: JSONPrinter.java, v 0.1 2016年7月28日 下午5:08:41 jiujie Exp $*/

public classJSONPrinter {privateObject jsonObj;/*** JSON文件打印器

* constructor

*@authorjiujie

* 2016年7月28日 下午5:08:59

*@paramjsonFile*/

publicJSONPrinter(File jsonFile) {this.jsonObj =jsonFile;

}/*** JSON字符串打印器

* constructor

*@authorjiujie

* 2016年7月28日 下午5:08:59

*@paramjsonString*/

publicJSONPrinter(String jsonString) {this.jsonObj =jsonString;

}public voidprint() {if (jsonObj instanceofFile) {try{

print(newFileInputStream((File) jsonObj));

}catch(Exception e) {

e.printStackTrace();

}

}else if (jsonObj instanceofString) {try{

print(newByteArrayInputStream(((String) jsonObj).getBytes()));

}catch(Exception e) {

e.printStackTrace();

}

}

}private void print(InputStream inputStream) throwsIOException {

InputStreamReader in= newInputStreamReader(inputStream);int read = 0;int indent = 0;while ((read = in.read()) > 0) {char ch = (char) read;switch(ch) {case '{': {

indent=printAndRightMove(indent, ch);break;

}case '}': {

indent=printAndLeftMove(indent, ch);break;

}case '[': {

indent=printAndRightMove(indent, ch);break;

}case ']': {

indent=printAndLeftMove(indent, ch);break;

}case ',': {

System.out.println(ch);

System.out.print(getBlankString(indent));break;

}default: {

System.out.print(ch);break;

}

}

}

in.close();

}private int printAndLeftMove(int indent, charch) {

System.out.println();

indent-= 2;

System.out.print(getBlankString(indent)+ch);returnindent;

}private int printAndRightMove(int indent, charch) {

System.out.println();

System.out.println(getBlankString(indent)+ch);

indent+= 2;

System.out.print(getBlankString(indent));returnindent;

}private String getBlankString(intlength) {if (length <= 0) {return "";

}

String blankString= "";for (int i = 0; i < length; i++) {

blankString+= " ";

}returnblankString;

}public static void main(String[] args) throwsFileNotFoundException, IOException {

ClassLoader classLoader= Vote.class.getClassLoader();

String path= classLoader.getResource("").toString().replace("/bin", "").replace("file:/","") + "src/json/json.txt";

JSONPrinter jsonPrinter= new JSONPrinter(newFile(path));

jsonPrinter.print();

JSONPrinter stringJsonPrinter= new JSONPrinter("{score:100,age:30}");

stringJsonPrinter.print();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值