【问题标题】:How to get key value from multiple nested json in Java如何从Java中的多个嵌套json中获取键值
【发布时间】:2021-01-20 06:17:33
【问题描述】:

我在我的应用程序中使用 Java。我想将多级嵌套的json和表单处理为键值对。

映射格式 1 定义为 Map

{
    "first_name": {
        "type": "string"
    },
    "date_of_birth": {
        "type": "date"
    },
    "last_name": {
        "type": "string"
    },
    "video": {
      "type": "nested", 
      "properties": {
        "id":    { "type": "integer"  },
        "title":     { "type": "string"   },
        "description":   { "type": "string"   }
      }
    },
    "address": {
        "type": "object",
        "properties": {
            "work": {
                "type": "string"
            },
            "home": {
                "type": "string"
            }
        }
    }
}

预期结果:

{
    "first_name": "string"  ,
    "date_of_birth": "date",
    "last_name": "string",
    "video.id": "integer",
    "video.title": "string",
    "video.description": "string",
    "address.work": "string",
    "address.home": "string"
}

映射格式2定义为Map

{
    "first_name": "string"
    "date_of_birth": "date"
    "last_name": "string"           
    "video": {
        "id": "integer",
        "title": "string",
        "description": string",
        "mpeg": {
            "format": "string",
            "name": "string"
        }
    },
    "address": {                
        "work": "string",               
        "home": "string"                
    }
}

预期结果:

{
    "first_name": "string",
    "date_of_birth": "date",
    "last_name": "string",
    "video.id": "integer",
    "video.title": "string",
    "video.description": "string",
    "video.description": "string",
    "video.mpeg.format": "string",
    "video.mpeg.name": "string",
    "address.work": "string",
    "address.home": "string"
}

如何在 Java 11 中使用 Map 获得上述预期结果?

【问题讨论】:

    标签: java json nested


    【解决方案1】:

    问题指出“json”是以Map<String, Object> 的形式收到的。这敲响了警钟:Object 是 Java 类层次结构的根,Object 类型的实例通常需要转换为要使用的 instanceof 类。在不了解地图值的实际类型的情况下,无法就如何使用它们提供建议。

    理想情况下,您应该使用 json 解析器将您的 json 转换为您可以查询的结构。周围有好几个。

    https://github.com/google/gson 为例解析器:

    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(input);
    

    要转换为您的地图,我建议使用递归算法来处理树结构。在伪代码中,它看起来像:

    addToMap(map, prefix, node)
         if node.key is 'type'
             put(prefix, node.value) in map
         else
             for each child node in node.value
                 addToMap(map, prefix + "." + node.key, child) 
    

    【讨论】:

    • 有没有办法使用 map 本身而不是 JsonParser?
    • @Galet 我会在答案中添加评论
    猜你喜欢
    • 1970-01-01
    • 2021-08-26
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多