java解析json
{"Dictionary":[{"Name":"事件大类","Code":"ComponetType"},{"Name":"告警级别","Code":"Severity"}],"ComponetType":[{"Name":"数据库","Code":"DataBase"},{"Name":"应用","Code":"App"},{"Name":"操作系统","Code":"OperateSystem"},{"Name":"中间件","Code":"MiddleWare"},{"Name":"网络","Code":"NetWork"},{"Name":"未知","Code":"Unknown"}],"Severity":[{"Name":"一级","Code":"1"},{"Name":"二级","Code":"2"},{"Name":"三级","Code":"3"},{"Name":"四级","Code":"4"},{"Name":"五级","Code":"5"}]}
此json串如何在java解析成如下格式,Dictionary是ComponetType和Severity父节点,需要附上代码。
谢谢!
ComponetType-事件大类
DataBase:数据库
App:应用
OperateSystem:操作系统
MiddleWare:中间件
NetWork:网络
Unknown:未知
Severity-告警级别
1:一级
2:二级
3:三级
4:四级
5:五级
Java
json
------解决方案-------------------- public static void main(String[] args) throws Exception {
File file = new File("f:/json.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int)file.length()];
String pageContent = new String(data, Charset.forName("GBK"));
JSONObject json = new JSONObject(pageContent);
JSONArray dList = json.getJSONArray("Dictionary");
String[][] dataList = getKeyValue(dList);
for (int i = 0, l = dataList.length; i < l; i++) {
System.out.println(dataList[i][0] + ":" + dataList[i][1]);
String[][] list = getKeyValue(json.getJSONArray(dataList[i][1]));
for (int j = 0, ll = list.length; j < ll; j++) {
System.out.println(list[j][0] + ":" + list[j][1]);
}
}
}
private static String[][] getKeyValue(JSONArray nodeList) throws
JSONException {
String[][] result = new String[nodeList.length()][2];
for (int i = 0, l = nodeList.length(); i < l; i++) {
JSONObject node = nodeList.getJSONObject(i);
result[i][0] = node.get("Name").toString();
result[i][1] = node.get("Code").toString();
}
return result;
}