java - 如何在java中使用GSON获取带有父前缀的嵌套json中的键

标签 java json gson

我尝试过以下示例。

public static void operate2(JsonElement jsonElement, List keys, JsonElement jsonElement2, String prefix){
String prefixnew = "";
if(jsonElement.isJsonArray()){

    JsonArray jsonArray = jsonElement.getAsJsonArray();

     for(int i=0; i<jsonArray.size(); i++){

         jsonElement = jsonArray.get(i);
         operate2(jsonElement, keys, jsonElement2, prefix);
     }

}else if(jsonElement.isJsonObject()){
     JsonObject jsonObject = jsonElement.getAsJsonObject();
     Set<Map.Entry<String,JsonElement>> childEntrySet = jsonObject.entrySet();


     for (Map.Entry<String, JsonElement> child: childEntrySet) {


         jsonElement2 = child.getValue();

         Object keyCheck = new Gson().fromJson(jsonElement2.toString(), Object.class);
         if (keyCheck instanceof Map) {
             prefix += child.getKey()+"_";
             keys.add(prefix);
             System.out.println("Map="+child.getKey());
         }else if (keyCheck instanceof Collection) {
             if(!prefix.equals("")){
                 prefix += child.getKey()+"_";
                 keys.add(prefix);
             }else{

                 prefix = child.getKey()+"_";
                 keys.add(prefix);
             }

             System.out.println("Collection="+child.getKey());

         }else{

             prefix += "";
         }
         operate2(jsonElement2, keys, jsonElement2, prefix);
     }

}else{
    prefix = "";
}

}

public static void test2(String json){


JsonElement jsonElement = new JsonParser().parse(json);
JsonElement jsonElement2 = null;
String prefix = "";
List keys = new ArrayList();
operate2(jsonElement, keys, jsonElement2, prefix);

Set keySet = new HashSet(keys);
System.out.println("Keys = "+keys);

}

我得到的输出 Keys = [items_, items_contact_, items_contact_records_, items_contact_records_recordings_, items_contact2_]

但我需要 items_、items_contact_、items_records_ ...。我们可以看到该记录不是联系人的子项,因此 items_contact_records_ 不应该在那里。相反,应该是 items_records_。

源 json 为

{
"items": [{
    "id": 633706061003,
    "fromNumber": "16572307534",

 "contact": {
     "id": 499354453003,
     "homePhone": "16572307534"
 },

"records": [{
    "id": 353389055003,
    "result": "LA",
    "recordings": [{
       "id": 16427622003
    }]
  }]
}],
"limit": 100,
"offset": 0,
"totalCount": 5949
}

最佳答案

我会使用以下方法:

  • 如果根元素不是json对象,则返回空列表
  • 否则迭代其其他条目,如果关联的值是对象或数组,则为每个条目添加键
  • 递归地获取值
<小时/>
public static List<String> operate(final JsonElement jsonElement, final String prefix, final boolean firstLayer) {
    if(jsonElement.isJsonObject() || (!firstLayer && jsonElement.isJsonArray())) {
        List<String> keys = new ArrayList<>();
        if(jsonElement.isJsonObject()) {
            JsonObject jObj = jsonElement.getAsJsonObject();
            for(Map.Entry<String, JsonElement> entry : jObj.entrySet()) {
                JsonElement value = entry.getValue();
                String newPrefix = prefix + entry.getKey();
                if(value.isJsonArray() || value.isJsonObject()) {
                    keys.add(newPrefix);
                    keys.addAll(operate(value, newPrefix + "_", false));
                }
            }
        } else {
            JsonArray array = jsonElement.getAsJsonArray();
            for(JsonElement element : array) {
                keys.addAll(operate(element, prefix, false));
            }
        }
        return keys;
    } else {
        return Collections.emptyList();
    }
}

测试方法:

public static void test(String json) {
    JsonElement jsonElement = new JsonParser().parse(json);
    List<String> keys = operate(jsonElement, "", true);
    System.out.println("Keys = " + keys);
}

在您的示例上运行它,您将得到:

Keys = [items, items_contact, items_records, items_records_recordings]

关于java - 如何在java中使用GSON获取带有父前缀的嵌套json中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34260038/

相关文章:

java - 使用 SQL 创建和构建复杂的座位结构?

java - 如何使用java获得weka中的最近邻居

jquery - $.getJSON 返回 "undefined"值,数据读取 [object Object]

php - 在Windows 7命令行窗口中通过PHP套接字发送JSON数据

javascript - 如何从变量中获取 JSON 值

android - Retrofit 2,解析json,忽略数组内部的错误数据类型

java - 如何将其转换为使用 java 流?

java - POI - 在 Excel 和 Java 日期之间转换的问题,反之亦然

android - 改造无法访问 HttpUrl

java - GSON 不序列化/反序列化扩展类