Firebase 序列化/反序列化的命名约定? [英] Naming convention with Firebase serialization/deserialization?

查看:26
本文介绍了Firebase 序列化/反序列化的命名约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Firebase 如何将 POJO 对象序列化/反序列化到/从 json,它是否使用 Jackson 或 Gson 或任何其他类似的库.
我在使用 Firebase 时遇到命名约定的问题.我的模型有点像这样:

I wonder to know how Firebase serialize/deserialize POJO object to/from json, does it use Jackson or Gson or any similar library else.
I have trouble about naming convention with Firebase. My model some like this:

class Data {
    private String someFieldName;
    private String anotherFieldName;
    public Data() {}
    public void setSomeFieldName(String) {...}
    public String getSomeFieldName(String) {...}
    public void setAnotherFieldName(String) {...}
    public String getAnotherFieldName() {...}
}

Firebase 中的预期结果应该是:

And the expected result in Firebase should be:

{
    "some_field_name" : "...",
    "another_field_name" : "..."
}

使用 Gson 我可以将 FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES 用于我的目的,就像在 Gson 文档中一样:

with Gson I can use FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES for my purpose, as in Gson doc:

以下是Java 字段名称"形式的一些示例--->JSON 字段名称":

Here's a few examples of the form "Java Field Name" ---> "JSON Field Name":

  • someFieldName --->some_field_name

  • someFieldName ---> some_field_name

_someFieldName --->_some_field_name

_someFieldName ---> _some_field_name

aStringField --->a_string_field

aStringField ---> a_string_field

网址 --->a_u_r_l

aURL ---> a_u_r_l


如何将我的 POJO 对象转换为Firebase 值"?使用特定的命名约定,反之亦然,或者有什么方法可以自定义序列化/反序列化过程?

谢谢!

推荐答案

当从 Firebase 数据库读回数据时,您可以使用 @PropertyName 批注来标记要在序列化时重命名的字段/反序列化,像这样:

When reading the data back from the Firebase database you can use the @PropertyName annotation to mark a field to be renamed when being serialized/deserialized, like so:

@IgnoreExtraProperties
class Data {
    @PropertyName("some_field_name")
    public String someFieldName
    @PropertyName("another_field_name")
    private String anotherFieldName;
    public Data() {}
}

确保您的字段是公开的而不是私有的,否则注释将不起作用(我也相信 Firebase 使用 Jackson 来处理引擎盖下的对象映射,但不要认为您实际上可以自定义它的使用方式).

Make sure that your field is public and not private or else the annotation will not work (I also believe that Firebase uses Jackson to handle the object mapping under the hood, but don't think you can actually customize HOW it uses it).

这篇关于Firebase 序列化/反序列化的命名约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆