如何在java中使用gson从嵌套的jsonobject中检索键和值?

时间:2017-03-09 17:48:05

标签: json gson

哪个是使用java中的gson库从复杂的嵌套jsonObject中检索所有键和值的最佳解决方案?

我想过以下面的方式实现它。但是对于复杂的嵌套jsonobject,迭代不断增加 如果element是JSON Object,则将其迭代为字段名称和JSON元素并处理这些JSON元素。 如果element是JSON Array,则将其迭代为JSON元素并处理这些JSON元素。 如果element是JSON Primitive,则将其值打印为String 例如。请找到我的样本json

{"address":{"name":"Deepa","street":"qwe","pincode":"234567","state":"Mumbai","country":"India"},"Foo":{"bar":{"id":"string","aa":"bb","aaa":"bbb","ccc":{"ddd":"eee","fff":"ggg","hh":"iii","duration":{"fromDate":"2015-04-13T00:00:00","toDate":"2015-05-27T00:00:00"},"firstCollectionDate":"2015-04-14T00:00:00"},"qqq":"zzz","ss":{"dd":"ff","tt":"wertyt"},"eerr":{"fffkjku":123,"cavcfgv":"ryty"},"sfgfg":{"memo":"hi","status":"open"}},"ffa":{}}}

1 个答案:

答案 0 :(得分:0)

使用可以递归地执行以下操作:

public static Object getValue(JSONObject jsonObject, String key)
{
    if(jsonObject.has(key))
    {
        return jsonObject.get(key);
    }

    Iterator<String> iterator = jsonObject.keys();
    while(iterator.hasNext())
    {
        Object value = jsonObject.get(iterator.next());
        if(value instanceof JSONObject)
        {
            return getValue((JSONObject) value, key);
        }
        else if(value instanceof JSONArray)
        {
            for(int i = 0; i < ((JSONArray) value).length(); i++)
            {
                return getValue(((JSONArray) value).getJSONObject(i), key);
            }
        }
    }
    return "not found";
}