用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 $
*/
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进行排版的更多相关文章
- Java集合 Json集合之间的转换
1. Java集合转换成Json集合 关键类:JSONArray jsonArray = JSONArray.fromObject(Object obj); 使用说明:将Java集合对象直接传进JSO ...
- Java对象 json之间的转换(json-lib)
在这里主要简单的介绍一下,如何使用json-lib这个工具包来完成Java对象(或集合)与json对象(或集合)之间的转换~ 1. Java对象转换成json(既创建json) 关键类:JSONObj ...
- Java 的 JSON 开源类库选择比较(zz)
在看了作者的介绍,然后我又到mvnrepository上去看了各个库的的使用数之后,发现只能在jackson和gson之间做选择. 以下是原文 有效选择七个关于Java的JSON开源类库 April ...
- java中json包的使用以及字符串,map,list,自定义对象之间的相互转换
做一个map和字符串的转换,需要导入这些jar包,这是最基本的一些jar包. 经过多方尝试得出结论入下: 首先导入基本包:json-lib-2.2.3-jdk15.jar 如果没有这个jar包,程序是 ...
- java系列--JSON数据的处理
http://blog.csdn.net/qh_java/article/details/38610599 http://www.cnblogs.com/lanxuezaipiao/archive/2 ...
- Java之JSON数据
特别注意:使用JSON前需要导包 操作步骤地址:http://blog.csdn.net/baidu_37107022/article/details/70876993 1.定义 JSON(JavaS ...
- JSON以及Java转换JSON的方法(前后端常用处理方法)
)); map.put("arr", new String[] { "a", "b" }); map.put("func" ...
- java处理json与对象的转化 递归
整个类是一个case,总结了我在使用java处理json的时候遇到的问题,还有级联关系的对象如何遍历,json和对象之间的转换! 对于对象json转换中遇到的问题我参考了一篇博客,http://blo ...
- 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 ...
随机推荐
- Struts2 实现分页
1.转自:http://www.cnblogs.com/shiyangxt/archive/2008/11/04/1316737.html环境:MyEclipse6.5+Mysql5+struts2. ...
- PGA突破pga_aggregate_target限制
SQL> show parameter pga NAME TYPE VALUE ------------------------------------ ----------- ...
- 【HDOJ】1247 Hat’s Words
字典树. #include <cstdio> #include <cstring> #include <cstdlib> #define MAXN 50005 #d ...
- bzoj3721
不是说好的20s吗,怎么我19s都超时……逗我最后还得写成c++才能过……首先不难发现询问肯定是O(1)的复杂度我们先把奇数和偶数分开排序,不难发现几个性质1. 奇数的个数一定是奇数2. 奇数选取随k ...
- 【模拟】NCPC 2014 E ceremony
题目链接: http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1791 题目大意: N栋大楼(N<=100000),拆除的时候有两种选择的操作,可 ...
- Delphi 重写控件的一个例子。
unit DBGridEx; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, ...
- 从大学开始学C++到现在的一些感悟
Since I choose this road, I will not regret it. --Mereyct 端午过后的第二天,闲着没事,更新一下博客. 写这个博客的原因是,看到了群里有 ...
- wordpress 404 error on all pages!
You have to enable mod_rewrite in apache itself or you won't be able to have permalinks the way you ...
- angularJS constant和value
angularJS可以通过constant(name,value)和value(name,value)对于创建服务也是很重要的. 相同点是:都可以接受两个参数,name和value. 区别: 1.co ...
- UIAlertView弹出框
<Alert弹出框提示用户信息> 1.遵循代理方法<UIAlertViewDelete> 2.调用方法UIAlertView *alert = [[UIAlertV ...