将动态JSON解析为Java中的对象

时间:2018-10-31 09:51:07

标签: java json gson

我有一个带有动态对象名称的怪异JSON。像这样

detailBeanA

此处masterA.xhtml{ "Sample_01": { "class": "Tenant", "A1": { "class": "Application", "template": "http" } }, "Sample_02": { "class": "Tenant", "A2": { "class": "Application", "template": "http" } } } 是动态的,该值可以是任何值。 Sample_01Sample_02属性也是如此。

现在如何将其解析为A1类?

我正在使用A1

只要在Java(Spring)中,也可以使用任何其他方式

2 个答案:

答案 0 :(得分:3)

您可以使用http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar中的JSONObject

public static void main(String[] args) {
        String input="{\r\n" + 
                "    \"Sample_01\": {\r\n" + 
                "        \"class\": \"Tenant\",\r\n" + 
                "        \"A1\": {\r\n" + 
                "            \"class\": \"Application\",\r\n" + 
                "            \"template\": \"http\"\r\n" + 
                "        }\r\n" + 
                "    },\r\n" + 
                "    \"Sample_02\": {\r\n" + 
                "        \"class\": \"Tenant\",\r\n" + 
                "        \"A2\": {\r\n" + 
                "            \"class\": \"Application\",\r\n" + 
                "            \"template\": \"http\"\r\n" + 
                "        }\r\n" + 
                "    }\r\n" + 
                "}";

        JSONObject jsonObject = new JSONObject(input);  


        Set<String> keys =jsonObject.keySet();
        for(String key:keys) {
            System.out.println("Key :: "+key +", Value :: "+jsonObject.get(key));;
        }
    }

如果您再次想解析Sample_01Sample_02Sample_XX的值,请检查jsonObject的实例,例如if(jsonObject.get(key) instanceof JSONObject)并重复循环

答案 1 :(得分:0)

扩展@Deepak添加的答案。 两种方法都是可行的,但是我更喜欢Gson,因为我已经在使用它。

使用JSONObject

JSONObject jsonObject = new JSONObject(input);  


Set<String> keys =jsonObject.keySet();
for(String key:keys) {
    System.out.println("Key :: "+key +", Value :: "+jsonObject.get(key));;
}

使用Gson

public static void main(String[] args) {

    String json = "{\"Sample_01\":{\"class\":\"Tenant\",\"A1\":{\"class\":\"Application\",\"template\":\"http\",\"serviceMain\":{\"class\":\"Service_HTTP\",\"virtualAddresses\":[\"10.0.1.10\"],\"pool\":\"web_poolddd\"},\"web_poolddd\":{\"class\":\"Pool\",\"monitors\":[\"http\"],\"members\":[{\"servicePort\":80,\"serverAddresses\":[\"192.0.13.10\",\"192.0.14.11\"]}]}}},\"Sample_20\":{\"class\":\"Tenant\",\"A1\":{\"class\":\"Application\",\"template\":\"http\",\"serviceMain\":{\"class\":\"Service_HTTP\",\"virtualAddresses\":[\"10.2.2.2\"],\"pool\":\"web_pool_data\"},\"web_pool_data\":{\"class\":\"Pool\",\"monitors\":[\"http\"],\"members\":[{\"servicePort\":80,\"serverAddresses\":[\"192.0.10.10\",\"192.0.10.11\"]}]}}}}";

    Type listType = new TypeToken<Map<String, Object>>(){}.getType();
    Gson gson = new Gson();
    Map<String,Object> myList = gson.fromJson(json, listType);

    JsonParser parser = new JsonParser();

    for (Map.Entry<String,Object> m : myList.entrySet())
    {
        System.out.println("==============");
        if(m.getValue() instanceof String){
            // get String value
        }else{ // if value is an Object

            System.out.println("VIP Sec: Name: "+m.getKey());
            Map<String,Object> myList1 = gson.fromJson(m.getValue().toString(), listType);
            for (Map.Entry<String,Object> m1 : myList1.entrySet())
            {
                if(!( m1.getValue() instanceof String)){
                    Map<String,Object> myList2 = gson.fromJson(m1.getValue().toString(), listType);
                    for (Map.Entry<String,Object> m2 : myList2.entrySet())
                    {
                         if(!( m2.getValue() instanceof String)){
                            Map<String,Object> myList3 = gson.fromJson(m2.getValue().toString(), listType);
                            for (Map.Entry<String,Object> m3 : myList3.entrySet())
                            {
                                if(m3.getKey().equals("virtualAddresses")){
                                    System.out.println("VIP Sec: IP Address: "+m3.getValue());
                                }
                                else if(m3.getKey().equals("pool")){
                                    System.out.println("Pool Sec: Name: "+m3.getValue());
                                }else if(m3.getKey().equals("monitors")){
                                    JsonArray monitors = parser.parse(m3.getValue().toString()).getAsJsonArray();
                                    int count = 0;
                                    while(count < monitors.size()){
                                        String monitor = monitors.get(count).getAsString();
                                        System.out.println("Monitor: "+monitor);
                                        count++;
                                    }
                                }else if(m3.getKey().equals("members")){
                                    JsonArray members = parser.parse(m3.getValue().toString()).getAsJsonArray();
                                    int count = 0;
                                    while(count < members.size()){
                                        // Parsing as Object to key values by key directly
                                        JsonObject mem = members.get(count).getAsJsonObject();
                                        String port = mem.get("servicePort").getAsString();
                                        System.out.println("Port: "+port);
                                        JsonElement ipAddrs = mem.get("serverAddresses");
                                        if(ipAddrs.isJsonArray()){
                                            JsonArray ips = ipAddrs.getAsJsonArray();
                                            int c = 0;
                                            while(c < ips.size()){
                                                String ip = ips.get(c).getAsString();
                                                System.out.println("IP: "+ip);
                                                c++;
                                            }
                                        }
                                        count++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}



OUTPUT:

==============
VIP Sec: Name: Sample_01
VIP Sec: IP Address: [10.0.1.10]
Pool Sec: Name: web_poolddd
Monitor: http
Port: 80.0
IP: 192.0.13.10
IP: 192.0.14.11
==============
VIP Sec: Name: Sample_20
VIP Sec: IP Address: [10.2.2.2]
Pool Sec: Name: web_pool_data
Monitor: http
Port: 80.0
IP: 192.0.10.10
IP: 192.0.10.11

详细了解第二种方法here