我从 PubSub 消息中获取 json。 Json 表示来自 Firestore 的文档(特定的 Firestore 数据模型以及定义字段类型的附加中间对象)。
我需要将这个特定的json映射到java pojo类。
我无法使用 Firestore API 直接从 Firestore 检索文档。
我的java课程
class Worker {
String name;
List<Instrument> instruments;
//getters , setters, constructor
}
class Instrument {
String instrumentName;
int cost;
//getters , setters, constructor
}
具体json(代表Firestore数据模型)
{
"name": {
"stringValue": "Bob"
},
"instruments": {
"arrayValue": {
"values": [
{
"mapValue": {
"fields": {
"instrumentName": {
"stringValue": "hummer"
},
"cost": {
"integerValue": "7"
}
}
}
},
{
"mapValue": {
"fields": {
"instrumentName": {
"stringValue": "screwdriver"
},
"cost": {
"integerValue": "5"
}
}
}
}
]
}
}
}
请问是否有一些java库可以转换它。我正在尝试常见的解决方案,例如 Jackson 和 Gson,但是,看起来它们可以很好地处理像这样的常规 json 表示
{
"name": "Bob",
"instrumens": [
{
"instrumentName": "hummer",
"cost": "7"
},
{
"instrumentName": "screwdriver",
"cost": "5"
}
]
}
但不是我之前描述的这种特定结构。 另外,我不想更改 pojo 类,添加那些中间对象,如“arrayValue”或“stringValue”。
最重要的是,我检查了 Firestore 是否具有 DocumentSnapshot 之类的类,并且我认为可以创建这样的快照(据我所知,它是特定 json - firestore 数据模型的代表),但是,再次看起来,它是可以仅将常规 json 转换为此类 DocumentSnapshot。 谢谢您的帮助。
我尝试使用 Jackson 和 Gson。但是,看起来不太适合这项任务。
您共享了两个数据库 JSON 结构。正如 @FrankvanPuffelen 在他的评论中已经提到的,第一个结构显示了 Firestore 文档的 gRPC 表示。据我所知,没有官方库可以帮助您将其与 POJO 类相互转换。但根据建议,您可以搜索替代方案或自己创建一个。
第二个实际上是以 DocumentSnapshot 对象的形式存在于文档中的数据的表示。这样的对象可以使用 toObject() 方法序列化到 Java 类或从 Java 类序列化,其中:
返回转换为 POJO 的文档内容,如果文档不存在,则返回 null。