Gson:跳过节点级别进行序列化

huangapple 未分类评论56阅读模式
英文:

Gson: skip node level for serialization

问题

I have some json which contains fields with custom names, e.g.:
{
   "user_id": 123,
   "user_name": "John",
   "field_with_custom_name_1": "value1",
   "field_with_custom_name_2": "value2",
   "field_with_custom_name_3": "value3"
}

For describe this json the next model was created:
public class UserData {
   
   @SerializedName("user_id")
   private int userId;

   @SerializedName("user_name")
   private String userName;

   private Map<String, String> customFields;
}

But after serialization we have json with the next structure:
{
   "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"
   }
}

Can you suggest how to ignore "customFields" level in the result?
英文:

I have some json which contains fields with custom names, e.g.:

{
   &quot;user_id&quot;: 123,
   &quot;user_name&quot;: &quot;John&quot;,
   &quot;field_with_custom_name_1&quot;: &quot;value1&quot;,
   &quot;field_with_custom_name_2&quot;: &quot;value2&quot;,
   &quot;field_with_custom_name_3&quot;: &quot;value3&quot;
}

For describe this json the next model was created:

public class UserData {
   
   @SerializedName(&quot;user_id&quot;)
   private int userId;

   @SerializedName(&quot;user_name&quot;)
   private String userName;

   private Map&lt;String, String&gt; customFields;
}

But after serialization we have json with the next structure:

{
   &quot;user_id&quot;: 123,
   &quot;user_name&quot;: &quot;John&quot;,
   &quot;customFields&quot;: {
      &quot;field_with_custom_name_1&quot;: &quot;value1&quot;,
      &quot;field_with_custom_name_2&quot;: &quot;value2&quot;,
      &quot;field_with_custom_name_3&quot;: &quot;value3&quot;
   }
}

Can you suggest how to ignore "customFields" level in the result?

答案1

得分: 0

你可以使用以下的注解来将一个字段从序列化和反序列化中排除:

@Expose(serialize = false, deserialize = false)
英文:

You can use the following annotation to exclude a field from serialization and deserialization:

@Expose (serialize = false, deserialize = false)

huangapple
  • 本文由 发表于 2020年3月15日 18:27:44
  • 转载请务必保留本文链接:https://java.coder-hub.com/60691910.html
匿名

发表评论

匿名网友

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

确定