Document.parse() 构造函数不适用于嵌套的 json 数组

Document.parse() constructor not working for nested json array

我有一个扩展的 json 字符串。

{"_id": {"oid": "59a47286cfa9a3a73e51e72c"}, "theaterId": {"numberInt": "101100"}, "location": {"address": {"street1": "340 XDW Market", "city": "Bloomington", "state": "MN", "zipcode": "12427"}, "geo": {"type": "Point", "coordinates": [{"$numberDouble": "-193.24565"}, {"$numberDouble": "144.85466"}]}}}

正在尝试将以上 json 字符串转换为文档以便将其插入 MongoDB。为此,我正在使用 org.bson.Document.Document.parse(json_string) 构造函数。

但是我在解析后得到的文档没有保留 geo.coordinate arraylist 中的数据类型(检查下面的文档)。虽然它保留了 theaterId.

的数据类型
{
    "_id": {
        "oid": "59a47286cfa9a3a73e51e72c"
    },
    "theaterId": {
        "numberInt": "101100"
    },
    "location": {
        "address": {
            "street1": "340 XDW Market",
            "city": "Bloomington",
            "state": "MN",
            "zipcode": "12427"
        },
        "geo": {
            "type": "Point",
            "coordinates": [-193.24565, 144.85466]
        }
    }
}

这是 Document.parse() API 中的潜在问题吗?

您在 geo.coordinate 中的字段以美元符号 $ 开头。在 theaterId 中你有 numberInt,而在坐标中 - $numberDouble.

检查 docs and 问题,了解如何根据您的需要处理它。考虑到 numberInt 看起来可以满足您的需求,您可能只需要从字段名称中删除美元。

编辑: 在深入研究了这些文档之后,您提供的那个 {"numberInt": "101100"} 没有扩展 json 数据类型,它只是具有 属性 和 属性 值的普通 json 对象。需要 {"$numberInt": "101100"} 才能扩展 json。另一方面 {"$numberDouble": "-193.24565"} 扩展。数据类型没有丢失,它被解析为 List<Double>,因为我们知道每个元素都是 Double 类型,数据类型可以重建回来。

如果您在 Document.toJson() 拍摄,在引擎盖下它正在使用 RELAXED 输出模式,它将输出您所看到的坐标 - [-193.24565, 144.85466]。如果你提供 EXTENDED 输出模式,例如像这样:

JsonWriterSettings settings = JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build();
System.out.println(document.toJson(settings));

然后数据类型将从 java 类型重建回来,坐标将如下所示:

[{"$numberDouble": "-193.24565"}, {"$numberDouble": "144.85466"}]

总之,Document.parse("json")没有问题,但你提供给它的json可能有问题。

编辑2: 如示例所示,可以从 java 类型重建数据类型。我不熟悉 collection.insertOne(Document.parse(json_string)) 背后的工作方式,但如果您没有明确指定模式,它可能默认使用 RELAXED,而不是 EXTENDED。文档 here 状态 - This format prioritizes type preservation at the loss of human-readability and interoperability with older formats.,所以它是有道理的。但这只是我的 胡乱猜测,您需要深入研究文档才能确定。