package com.test.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.Set;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class test {
public static void main(String[] args) {
// analysis();
analysisTextFile();
}
/**
* 解析 项目中的json文本文件
*/
private static void analysisTextFile() {
//这个我是用的txt文件内容是 json格式 通过文件名称获取文件所在的绝对路径
URL welcomeFile = JsonUtil.class.getClassLoader().getResource("json.txt");
String url = welcomeFile.toString().replace("file:/", "");
File file = new File (url);
try {
FileReader fileReader = new FileReader (file);
BufferedReader br = new BufferedReader (fileReader);
StringBuffer sb = new StringBuffer (100);
String str;
boolean firstLine = true;
while ((str = br.readLine ()) != null) {
if (firstLine) {
sb.append (str);
firstLine = false;
} else {
sb.append ("\n").append (str);
}
}
System.out.println (sb.toString ());
JSONObject json = JSONObject.parseObject (sb.toString ());
Set<String> it = json.keySet ();
for ( String jsonKey : it ) {
JSONArray jsonArray = json.getJSONArray (jsonKey);
if (null!=jsonArray) {
for ( int i = 0 ; i < jsonArray.size () ; i++ ) {
JSONObject urlJson = jsonArray.getJSONObject (i);
Set<String> urlSet = urlJson.keySet ();
for ( String apiUrl : urlSet ) {
System.out.println(apiUrl + "=============" + jsonKey );
System.out.println(apiUrl + "=============" + urlJson.getString(apiUrl));
}
}
}
}
br.close ();
fileReader.close ();
} catch (Exception e) {
System.out.println (" Read welcome file error:" + e.getMessage ());
}
}
/**
* 在不知道所有对象key的时候 去解析整个json字符串
*/
private static void analysisText() {
JSONObject json = JSONObject.parseObject("{ \"test\": [{ \"msg\": \"0\" }, { \"register\": \"0\" } ] }");
//获取json对象中的所有二级 keyName
Set<String> it = json.keySet();
for (String jsonKey : it) {
//根据keyName 获取该对象的值 (json数组)
JSONArray jsonArray = json.getJSONArray(jsonKey);
if (null != jsonArray) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject urlJson = jsonArray.getJSONObject(i);
Set<String> urlSet = urlJson.keySet();
for (String apiUrl : urlSet) {
System.out.println(apiUrl + "=============" + jsonKey );
System.out.println(apiUrl + "=============" + urlJson.getString(apiUrl));
}
}
}
}
}
}