Skrytz
Skrytz

Reputation: 31

Saving Jsonified Java Objects in 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?

Upvotes: 0

Views: 289

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317760

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.

Upvotes: 3

Related Questions