如何使用java在Json String中动态更改Key的值

时间:2015-05-28 09:28:16

标签: java

我试图用java解析Json字符串,我已经遇到了一些情况。

见下面是我的JSON字符串:

"NetworkSettings": {
                "Ports": {
            "8080/tcp": [   // It will change dynamically like ("8125/udp" and "8080/udp" etc....)
                {
                    "HostIp": "0.0.0.0",
                    "HostPort": "8080"
                }
            ]
        }
    }

我尝试使用以下代码解析上面的json字符串:

JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
                {
                    JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
                    if(ntw_Ports_obj.has("8080/tcp"))
                    {
                        JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");                          
                        JsonObject ntwtcp_obj=arr_ntwtcp.get(0).getAsJsonObject();
                        if(ntwtcp_obj.has("HostIp"))
                        {
                            ntw_HostIp=ntwtcp_obj.get("HostIp").toString();
                            System.out.println("Network HostIp = "+ntw_HostIp);
                        }
                        if(ntwtcp_obj.has("HostPort"))
                        {
                            ntw_HostPort=ntwtcp_obj.get("HostPort").toString();                     
                            System.out.println("Network HostPort = "+ntw_HostPort);
                        }
                    }
                    else
                    {
                        ntw_HostIp="NA";
                        ntw_HostPort="NA";
                    }
                }
                else
                {
                    ntw_HostIp="NA";
                    ntw_HostPort="NA";
                }  

在我的代码中,我使用了这段代码

JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");

获取" 8080 / tcp"

的值

如何获得动态更改键的值,如(" 8125 / udp"," 8134 / udp"等...)

注意:我使用gson库进行解析

修改后

public static void main(String args[])
    {
        try
        {
            JsonParser parser = new JsonParser();
            JsonObject obj=(JsonObject)parser.parse(new FileReader("sampleJson.txt"));
            System.out.println("obj = "+obj);
            JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
            if(NetworkSettings_obj.has("Ports"))
            {
                JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
                System.out.println("ntw_Ports_obj = "+ntw_Ports_obj);
                Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
                List keys = new ArrayList();
                System.out.println(keyObjects instanceof Map);  //**** here the statement prints false
                if (keyObjects instanceof Map)        // *** so controls doesn't enters into the if() condition block *** //
                {
                    Map map = (Map) keyObjects;
                    System.out.println("Map = "+map);
                    keys.addAll(map.keySet());
                    String key = (String) keys.get(0);
                    JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
                    System.out.println("Array List = "+jArray);
                }
            }
        }
        catch(Exception e)
        {

        }

    }

2 个答案:

答案 0 :(得分:1)

您可以做类似的事情(未经测试但应该没问题):

if (ntw_Ports_obj.isJsonArray()) {

   Iterator it = ntw_Ports_obj.getAsJsonArray().iterator();

   while (it.hasNext()) {

     JsonElement element = (JsonElement) it.next();

     if(element.isJsonArray()){

      JsonArray currentArray = element.getAsJsonArray();

      // Do something with the new JsonArray...

     }

   }
 }

答案 1 :(得分:0)

所以你的问题是关键8080/tcp没有修复,它可能会改变。在这种情况下,你可以尝试这样来获得Dynamic key的价值。

Set<Map.Entry<String, JsonElement>> entrySet = ntw_Ports_obj
                .entrySet();

for (Map.Entry<String, JsonElement> entry : entrySet) {
    String key = entry.getKey();
    JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
    System.out.println(jArray);
}

修改

Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();

/** for the given json there is a one json object within the 'Ports' so the 'keyObjects' will be the 'Map'**/
if (keyObjects instanceof Map) {
    Map map = (Map) keyObjects;
    keys.addAll(map.keySet());
    /**
     * keys is a List it may contain more than 1 value, but for the given
     * json it will contain only one value
     **/
    String key = (String) keys.get(0);
    JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
    System.out.println(jArray);
}