之前听到朋友的面试题,是如何对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 $
*/
public class JSONPrinter { private 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();
}
} else if (jsonObj instanceof String) {
try {
print(new ByteArrayInputStream(((String) jsonObj).getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}
} private void print(InputStream inputStream) throws IOException { InputStreamReader in = new InputStreamReader(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, 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 "";
}
String blankString = "";
for (int i = 0; i < length; i++) {
blankString += " ";
}
return blankString;
} public static void main(String[] args) throws FileNotFoundException, IOException {
ClassLoader classLoader = Vote.class.getClassLoader();
String path = classLoader.getResource("").toString().replace("/bin", "").replace("file:/",
"") + "src/json/json.txt";
JSONPrinter jsonPrinter = new JSONPrinter(new File(path));
jsonPrinter.print(); JSONPrinter stringJsonPrinter = new JSONPrinter("{score:100,age:30}");
stringJsonPrinter.print();
} }

输出

{
{
"name":"perfumeType",
"values":
[
"EDT",
"EDP"
],
"countMap":
{
"EDT":,
"EDP":
}
}
]
}
{
score:,
age:
}

用JAVA给JSON进行排版的更多相关文章

  1. Java集合 Json集合之间的转换

    1. Java集合转换成Json集合 关键类:JSONArray jsonArray = JSONArray.fromObject(Object obj); 使用说明:将Java集合对象直接传进JSO ...

  2. Java对象 json之间的转换(json-lib)

    在这里主要简单的介绍一下,如何使用json-lib这个工具包来完成Java对象(或集合)与json对象(或集合)之间的转换~ 1. Java对象转换成json(既创建json) 关键类:JSONObj ...

  3. Java 的 JSON 开源类库选择比较(zz)

    在看了作者的介绍,然后我又到mvnrepository上去看了各个库的的使用数之后,发现只能在jackson和gson之间做选择. 以下是原文 有效选择七个关于Java的JSON开源类库 April  ...

  4. java中json包的使用以及字符串,map,list,自定义对象之间的相互转换

    做一个map和字符串的转换,需要导入这些jar包,这是最基本的一些jar包. 经过多方尝试得出结论入下: 首先导入基本包:json-lib-2.2.3-jdk15.jar 如果没有这个jar包,程序是 ...

  5. java系列--JSON数据的处理

    http://blog.csdn.net/qh_java/article/details/38610599 http://www.cnblogs.com/lanxuezaipiao/archive/2 ...

  6. Java之JSON数据

    特别注意:使用JSON前需要导包 操作步骤地址:http://blog.csdn.net/baidu_37107022/article/details/70876993 1.定义 JSON(JavaS ...

  7. JSON以及Java转换JSON的方法(前后端常用处理方法)

    )); map.put("arr", new String[] { "a", "b" }); map.put("func" ...

  8. java处理json与对象的转化 递归

    整个类是一个case,总结了我在使用java处理json的时候遇到的问题,还有级联关系的对象如何遍历,json和对象之间的转换! 对于对象json转换中遇到的问题我参考了一篇博客,http://blo ...

  9. Java JWT: JSON Web Token

    Java JWT: JSON Web Token for Java and Android JJWT aims to be the easiest to use and understand libr ...

随机推荐

  1. Delphi调用WINAPI时到底应该是指针还是结构体(注意是Delphi变量本身就是指针)

    看MSDN,GetWindowRect的说明如下: BOOL WINAPI GetWindowRect( _In_  HWND   hWnd, _Out_ LPRECT lpRect // 注意,没* ...

  2. paip.提升用户体验-----c++ gcc 命令在notepad++扩展中的配置..

    paip.提升用户体验-----c++ gcc 命令在notepad++扩展中的配置.. 作者Attilax ,  EMAIL:1466519819@qq.com  来源:attilax的专栏 地址: ...

  3. 实战weblogic集群之创建节点和集群

    一.启动weblogic,访问控制台 weblogic的domain创建完成后,接下来就可以启动它,步骤如下: $ cd /app/sinova/domains/base_domain/bin $ . ...

  4. 高等数学(拉格朗日乘子法):NOI 2012 骑行川藏

    [NOI2012] 骑行川藏 输入文件:bicycling.in   输出文件:bicycling.out   评测插件 时间限制:1 s   内存限制:128 MB NOI2012 Day1 Des ...

  5. HDOJ(HDU) 2107 Founding of HDU(找最大值)

    Problem Description 经过慎重的考虑,XHD,8600, LL,Linle以及RPG等ACM队员集体退役,甚至正在酝酿退学. 为什么?要考研?那也不用退学呀- 当然不是!真正的原因是 ...

  6. [操作系统] OS X Yosemite U盘制作

    话不多说,DiskMakerX,大小6.3M,下载地址:http://www.liondiskmaker.com/,然后准备好U盘和从官网下的Yosemite系统就可以开始了. DiskMaker X ...

  7. XQuery FLWOR 表达式

    FLWOR 是 "For, Let, Where, Order by, Return" 的只取首字母缩写.for 语句把 bookstore 元素下的所有 book 元素提取到名为 ...

  8. listview 遇到问题java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

    开发的时候 遇到 java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 这个异常有时候会有,有时候正常 不太好捕捉 猜测 已经 ...

  9. WinFrom玩转config配置文件

    本文转载:http://www.dotblogs.com.tw/sam319/archive/2010/01/01/12753.aspx 有時候我們希望程式可以記下使用者的設定    下次開啟時可以繼 ...

  10. spring mvc使用ClassPathXmlApplicationContext或FileSystemXmlApplicationContext和XmlWebApplicationContext类的操作其中 XmlWebApplicationContext是专为Web工程定制的。

    一.简单的用ApplicationContext做测试的话,获得Spring中定义的Bean实例(对象).可以用: ApplicationContext ac = new ClassPathXmlAp ...