GET 요청을 통해 읽어들인 JSON 형태의 데이터에서 Key 들을 추출하는 소스이다. 재귀로 작성했고, 특이 사항은 다음과 같다.
public static void main(String[] args) {
String jsonString = null;
HttpURLConnection con = null;
BufferedReader in = null;
try {
URL url = new URL("my url");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
jsonString = content.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
JSONObject jsonObject = new JSONObject(jsonString);
Map<String, String> jsonMap = new TreeMap<>();
setJsonMap(jsonMap, "", jsonObject, 10);
System.out.println(jsonMap);
}
public static void setJsonMap(Map<String, String> jsonMap, String parentKey, JSONObject jsonObject, Integer arrayMaxLength) {
Iterator iter = jsonObject.keys();
while (iter.hasNext()) {
String key = (String) iter.next();
Object object = jsonObject.get(key);
String myKey = parentKey + key;
if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.length() && i < arrayMaxLength; i++) {
Object arrayObject = jsonArray.get(i);
if (arrayObject instanceof JSONObject) {
setJsonMap(jsonMap, myKey + "[" + i + "].", (JSONObject) arrayObject, arrayMaxLength);
} else {
jsonMap.put(myKey, object.toString());
}
}
} else if (object instanceof JSONObject) {
setJsonMap(jsonMap, myKey + ".", (JSONObject) object, arrayMaxLength);
} else {
jsonMap.put(myKey, object.toString());
}
}
}