在平时开发过程中,无论是自己拼接的json还是从服务器获取的json,我们往往会使用一个在线格式化工具
这个工具不仅可以快速的查看该字符串是否是合法的json,也对这个字符串进行了整理,整理之后的字符串我们可以轻松看到key和value所对应的值。
(1)判断是否是json或json数组
/**
* 判断是否是json
* @param s
* @return
*/
public static boolean isJson(String s){
Object json = null;
try {
json = new JSONTokener(s).nextValue();
} catch (JSONException e) {
e.printStackTrace();
}
if(json instanceof JSONObject){
return true;
}
return false;
}
/**
* 判断是否是json数组
* @param s
* @return
*/
public static boolean isJsonArray(String s){
Object json = null;
try {
json = new JSONTokener(s).nextValue();
} catch (JSONException e) {
e.printStackTrace();
}
if (json instanceof JSONArray){
return true;
}
return false;
}
(2)json的格式化
/**
* 添加制表符
* @param level
* @return
*/
private static String getLevelStr(int level) {
StringBuffer levelStr = new StringBuffer();
for (int levelI = 0; levelI < level; levelI++) {
levelStr.append("\t");
}
return levelStr.toString();
}
/**
* 获取格式化之后的字符串
* @param json 可能是json也有能是json数组
* @return
*/
public static StringBuffer getJsonForMatStr(String json){
int level = 0;
//存放格式化的json字符串
StringBuffer jsonForMatStr = new StringBuffer();
for(int index=0;index<json.length();index++){//将字符串中的字符逐个按行输出
//获取s中的每个字符
char c = json.charAt(index);
if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
//换行时添加制表符
jsonForMatStr.append(getLevelStr(level));
}
//遇到"{"和"["要增加空格和换行,遇到"}"和"]"要减少空格,以对应,遇到","要换行
switch (c) {
case '{':
case '[':
jsonForMatStr.append(c + "\n");
level++;
break;
case ',':
jsonForMatStr.append(c + "\n");
break;
case '}':
case ']':
jsonForMatStr.append("\n");
level--;
jsonForMatStr.append(getLevelStr(level));
jsonForMatStr.append(c);
break;
default:
jsonForMatStr.append(c);
break;
}
}
return jsonForMatStr;
}
(3)演示效果
我们用代码封装一个json数组
JsonObject jsonObject1 = new JsonObject();
jsonObject1.addProperty("key1", "1111");
jsonObject1.addProperty("key2", "2222");
jsonObject1.addProperty("key3", "3333");
jsonObject1.addProperty("key4", "4444");
jsonObject1.addProperty("key5", "5555");
JsonObject jsonObject2 = new JsonObject();
jsonObject2.addProperty("key1", "1111");
jsonObject2.addProperty("key2", "2222");
jsonObject2.addProperty("key3", "3333");
jsonObject2.addProperty("key4", "4444");
jsonObject2.addProperty("key5", "5555");
JsonArray jsonElements = new JsonArray();
jsonElements.add(jsonObject1);
jsonElements.add(jsonObject2);
获取该json数组的字符串形式
[{"key1":"1111","key2":"2222","key3":"3333","key4":"4444","key5":"5555"},{"key1":"1111","key2":"2222","key3":"3333","key4":"4444","key5":"5555"}]
我们发现默认的json格式是一个没有空格,没有换行符,没有制表符的字符串,并且只有一行,这样的格式很慢轻松的找到key和value的对应关系,这时我们需要对字符串进行格式化
格式化之后的效果大致如下:
[
{
"key1":"1111",
"key2":"2222",
"key3":"3333",
"key4":"4444",
"key5":"5555"
},
{
"key1":"1111",
"key2":"2222",
"key3":"3333",
"key4":"4444",
"key5":"5555"
}
]
json格式化之后依然是一个合法的json。