java根据key获取任意json结构的值

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author cangyue
 */
public class Example {

    public static void main(String[] args) {
        String json = "{\n"
                + "    \"Response\": {\n"
                + "        \"InstanceIdSet\": [\n"
                + "            \"xxx1\",\n"
                + "            \"xxx2\"\n"
                + "        ],\n"
                + "        \"RequestId\": \"eac6b301-a322-493a-8e36-83b295459397\"\n"
                + "    }\n"
                + "}";
        JSONObject object1 = JSONObject.parseObject(json);

        List list = new ArrayList<>();
        list.add(object1);
        System.out.println(t(list, "InstanceIdSet"));
    }

    public static Object t(List object, String key) {
        List list = new ArrayList<>();
        JSONObject objJSON;
        JSONArray array;
        Object v;
        for (Object obj : object) {
            if (obj instanceof JSONArray) {
                array = (JSONArray) obj;
                for (int x = 0, y = array.size(); x < y; x++) {
                    if (array.get(x) instanceof JSONObject) {
                        list.add(array.get(x));
                    }
                }
            }
            if (obj instanceof JSONObject) {
                objJSON = (JSONObject) obj;
                for (String s : objJSON.keySet) {
                    v = objJSON.get(s);
                    if (Objects.equals(s, key)) {
                        return v;
                    }
                    if (v instanceof JSONObject | v instanceof JSONArray) {
                        list.add(v);
                    }
                }
            }
        }
        if (list.isEmpty()) {
            return null;
        }
        return t(list, key);
    }
}
 
  

你可能感兴趣的:(java)