IT/Java & JSP & FW

java :: JSON DATA 원하는 값 MAP 형태로 리턴시키기.

엑수시아 2012. 12. 10. 14:44

전번 xml 탐사에 이은 json 탐사 입니다.
java 단에서 다 불러오는 거구요.
방식은 재귀 호출로 원하는 값을 Map형태로 담아서 리턴합니다.

선언부는 아래와 같이.

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

한번 살펴 보시면 좋을껏 같습니다. ^^ 

	/** JSON URL 호출 **/
	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}
	/** 호출할 json URL 입력(시작메소드) **/
	public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
		InputStream is = null;
		try {
			is = new URL(url).openStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("EUC-KR")));
			String jsonText = readAll(rd);
			JSONObject json = new JSONObject(jsonText);
			return json;
		} finally {
			is.close();
		}
	}
	public Object getJSON(String json, String searchWord, Map<String, Object> resultMap) {  //Json DATA 전 영역 탐사 및 원하는 데이터를 Map 형태로 리턴시킴
		JSONObject jsonObj = null;
		try {
			jsonObj = new JSONObject(json);
			Iterator itr = jsonObj.keys();
			int countJSON = 0;
			while (itr.hasNext()) {
				
				String key = (String)itr.next();
				Object value = jsonObj.get(key);
				String selecter = (String)value.toString();
				
				if(key.equals(searchWord)){  // 조건에 걸린 word 값을 찾아서 map 형태로 리턴
					resultMap.put(key, value);
				}
				
				if(selecter != null && !selecter.equals("") && !selecter.equals("null") && jsonObj.get(key) instanceof JSONArray){
					if((JSONArray)jsonObj.get(key) instanceof JSONArray){
						JSONArray jsonArray = (JSONArray)jsonObj.get(key);
						//this.logger.debug(jsonArray.toString());
						for(int i = 0 ; i<jsonArray.length() ; i++){
							jsonArray.get(i);
							JSONObject jsonObj2 = new JSONObject(jsonArray.get(i).toString());
							getJSON(jsonObj2.toString(), searchWord, resultMap);
						}
					}
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultMap;
	}
	//소스제공 :: http://zion437.tistory.com (by. 엑수시아)