用递归方式解析JSONObject 为HashMap

package com.crunii.mp.cqga;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import org.apache.commons.httpclient.HttpException;

import net.sf.json.JSONArray;

import net.sf.json.JSONException;

import net.sf.json.JSONObject;

public class TestMain {

/**

* @param args

* @throws IOException

* @throws HttpException

*/

public static void main(String[] args) throws Exception {

InputStream ins = TestMain.class.getResourceAsStream("/data/json.txt");

BufferedReader br = new BufferedReader(new InputStreamReader(ins, "utf-8"));

StringBuffer sb = new StringBuffer();

String temp = null;

while ((temp = br.readLine()) != null) {

sb.append(temp);

}

Map<String, Object> map = jsonStrToMap(sb.toString());

System.err.println(map);

}

public static Map<String, Object> jsonStrToMap(String json) throws JSONException {

JSONObject jsonResult = JSONObject.fromObject(json);

Map<String, Object> result = jsonOjbToMap(jsonResult);

return result;

}

private static List<Object> jsonArrToList(JSONArray jsonArray) throws JSONException {

List<Object> list = new ArrayList<Object>();

for (int i = 0; i < jsonArray.size(); i++) {

Object val = jsonArray.get(i);

if (!(val instanceof JSONObject) && !(val instanceof JSONArray)) {

list.add(val);

continue;

}

if (val instanceof JSONObject) {

Map<String, Object> map = jsonOjbToMap((JSONObject) val);

list.add(map);

continue;

}

if (val instanceof JSONArray) {

list.add(jsonArrToList((JSONArray) val));

continue;

}

}

return list;

}

private static Map<String, Object> jsonOjbToMap(JSONObject jsonResult) throws JSONException {

Map<String, Object> result = new HashMap<String, Object>();

Iterator<String> keyIt = jsonResult.keys();

while (keyIt.hasNext()) {

String key = keyIt.next();

Object val = jsonResult.get(key);

if (!(val instanceof JSONObject) && !(val instanceof JSONArray)) {

result.put(key, val);

continue;

}

if (val instanceof JSONObject) {

Map<String, Object> valMap = jsonOjbToMap((JSONObject) val);

result.put(key, valMap);

continue;

}

if (val instanceof JSONArray) {

JSONArray ja = (JSONArray) val;

result.put(key, jsonArrToList(ja));

}

}

return result;

}

}

猜你喜欢

转载自laowang1984.iteye.com/blog/2259618