将Json格式的Java对象保存在Firestore中

huangapple go评论69阅读模式
英文:

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&lt;String, Object&gt; and provide that to set() or update(). Similar when reading the documents - you will be provided with a Map to copy fields out of.

huangapple
  • 本文由 发表于 2020年10月7日 06:39:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64234737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定