【问题标题】:Gson: skip node level for serializationGson:跳过节点级别进行序列化
【发布时间】:2020-03-15 10:27:44
【问题描述】:

我有一些包含自定义名称字段的 json,例如:

{
   "user_id": 123,
   "user_name": "John",
   "field_with_custom_name_1": "value1",
   "field_with_custom_name_2": "value2",
   "field_with_custom_name_3": "value3"
}

为了描述这个 json,创建了下一个模型:

public class UserData {

   @SerializedName("user_id")
   private int userId;

   @SerializedName("user_name")
   private String userName;

   private Map<String, String> customFields;
}

但是在序列化之后,我们得到了具有下一个结构的 json:

{
   "user_id": 123,
   "user_name": "John",
   "customFields": {
      "field_with_custom_name_1": "value1",
      "field_with_custom_name_2": "value2",
      "field_with_custom_name_3": "value3"
   }
}

您能否建议如何忽略结果中的“customFields”级别?

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    您可以使用以下注解将字段排除在序列化和反序列化之外:

    @Expose (serialize = false, deserialize = false)
    

    【讨论】:

    • Expose 排除整个节点,结果将是下一个: { "user_id": 123, "user_name": "John" } 但需要:{ "user_id": 123, "user_name": “约翰”、“field_with_custom_name_1”:“value1”、“field_with_custom_name_2”:“value2”、“field_with_custom_name_3”:“value3”}
    • 不,因为字段名称和编号不是恒定的
    • @noChangesAdded 我的意思是首先你可以序列化 json 中的对象,然后操作 json 以展平它包含的任何数组。
    猜你喜欢
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多