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();
}
}