英文:
Saving Jsonified Java Objects in Firestore
问题
这里有没有一种方法来处理将一个POJO类,将其写入JSON字符串并保存到Firestore的过程?
我知道可以将POJO类保存到Firestore,然而,我的许多类都有诸如JsonIgnore,JsonProperty等注释。
例如,我可以有以下类:
@Data
public class Player {
@JsonIgnore
private String id;
@JsonProperty("playersName")
private String name;
@JsonProperty("playersAge")
private String age;
}
如果我直接将这个POJO保存到Firestore,我会得到以下结果:
id: "12345"
name: "John Doe"
age: "30"
如果我将其转换为JSON字符串,它会看起来类似于这样,我想将其保存到Firestore中:
{
"playersName": "John Doe"
"playersAge": "30"
}
在Firestore中,我想将其保存为上述JSON字符串:
playersName: "John Doe"
playersAge: "30"
然而,Firestore不允许保存原始类型/数组,那么实现上述目标的最佳方法是什么?
英文:
Is there a way to go about taking a POJO class, writing it into a JSON string and saving it to Firestore?
I know it is possible to save POJO classes to Firestore, however, a lot of my classes have annotations such as JsonIgnore, JsonProperty etc.
For example I could have the following class
@Data
public class Player {
@JsonIgnore
private String id;
@JsonProperty("playersName")
private String name;
@JsonPropety("playersAge")
private String age;
}
If I save this POJO directly into Firestore, I will get the following
id: "12345"
name: "John Doe"
age: "30"
If I convert it to JSON string it will look along something like this, which I would like to save into Firestore
{
"playersName": "John Doe"
"playersAge": "30"
}
In Firestore I would like to save it as the above JSON string
playersName: "John Doe"
playersAge: "30"
However, Firestore doesn't allow to save primitives/arrays, so what would be the best approach to wanting to accomplish the above?
答案1
得分: 2
Firestore有自己的注解,用于忽略POJO成员或更改其名称。查看@Exclude,作为@JsonIgnore的等效注解。还可以查看注解@PropertyName、@IgnoreExtraProperties和@ThrowOnExtraProperties。
(请注意,我链接到了Android API的注解。如果您使用的是Java服务器SDK,它们将存在于不同的包中,例如@Exclude。)
如果您不使用这些注解,您将需要手动将要保存到文档中的字段复制到Map<String, Object>
,并将其提供给set()
或update()
。在读取文档时类似,会提供一个Map供您复制字段。
英文:
Firestore has its own annotations for ignoring POJO members or changing their names. Look into @Exclude as an equivalent to @JsonIgnore. Also see annotations @PropertyName, @IgnoreExtraProperties, and @ThrowOnExtraProperties.
(Note that I linked to the Android API annotations. If you're using the Java server SDK, they will exist in a different package, e.g. @Exclude.)
If you don't use these annotations, you will instead have to manually copy the fields you want to save into the document using a Map<String, Object>
and provide that to set()
or update()
. Similar when reading the documents - you will be provided with a Map to copy fields out of.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论