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



我有一个扩展的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数组列表中保留数据类型(请查看下面的文档(。同时保留了CCD_ 2的数据类型。

{
"_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中的字段以美元符号$开头。在terId中有numberInt,而在坐标-$numberDouble中。

查看文档和这个问题,了解如何根据您的需要处理它。考虑到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可能有问题。

Edit2:如示例中所示,数据类型可以从java类型重建回来。我不熟悉collection.insertOne(Document.parse(json_string))在后台的工作方式,但如果您没有明确指定模式,默认情况下可能会使用RELAXED,而不是theaterId0。这里的文档状态为-This format prioritizes type preservation at the loss of human-readability and interoperability with older formats.,所以这是有意义的。但这只是我的猜测,你需要深入研究文档才能确定。

最新更新