JSON의 모든 KEY 가져오기

JSON의 모든 KEY를 반복적으로 이동합니다.
JSON 형식은 다음과 같습니다.
{"username":"tom", "age":18,address":[{"province":"상하이시"}, {"city":"상하이시"}, {"disrtict":"정안구"}]}
처리 후 결과는 다음과 같습니다.
address|province|city|disrtict|username|age
package ai.advance.until;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;

public class fastJsonDiff {
    /**
     *        key
     *
     * @param jsonObject
     */
    public static StringBuffer getAllKey(JSONObject jsonObject) {
        StringBuffer stringBuffer = new StringBuffer();
        Iterator keys = jsonObject.keySet().iterator();// jsonObject.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            stringBuffer.append(key.toString()).append("|");
            if (jsonObject.get(key) instanceof JSONObject) {
                JSONObject innerObject = (JSONObject) jsonObject.get(key);
                stringBuffer.append(getAllKey(innerObject));
            } else if (jsonObject.get(key) instanceof JSONArray) {
                JSONArray innerObject = (JSONArray) jsonObject.get(key);
                stringBuffer.append(getAllKey(innerObject));
            }
        }
        return stringBuffer;
    }

    public static StringBuffer getAllKey(JSONArray json1) {
        StringBuffer stringBuffer = new StringBuffer();
        if (json1 != null ) {
            Iterator i1 = json1.iterator();
            while (i1.hasNext()) {
                Object key = i1.next();
                if (key instanceof  JSONObject) {
                    JSONObject innerObject = (JSONObject) key;
                    stringBuffer.append(getAllKey(innerObject));
                } else if (key instanceof JSONArray) {
                    JSONArray innerObject = (JSONArray) key;
                    stringBuffer.append(getAllKey(innerObject));
                }else{
                }
            }
        }
        return stringBuffer;
    }

    private final static String st1 = "{\"username\":\"tom\",\"age\":18,\"address\":[{\"province\":\"   \"},{\"city\":\"   \"},{\"disrtict\":\"   \"}]}";
    private final static String st2 = "{username:\"tom\",age:18}";

    public static void main(String[] args) {
        System.out.println(st1);
        JSONObject jsonObject1 = JSONObject.parseObject(st1);
        StringBuffer stb = getAllKey(jsonObject1);
        System.err.println(stb);

    }

}

좋은 웹페이지 즐겨찾기