多个GSON @SerializedName每个字段? [英] Multiple GSON @SerializedName per field?

查看:1357
本文介绍了多个GSON @SerializedName每个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Gson有什么方法可以将多个JSON字段映射到单个Java对象成员变量吗?



假设我有一个Java类...

  public class MyClass {
String id;
字符串名称;
}

我想用两个不同的服务来使用这个类。然而,这两种服务在返回数据方面有所不同......

  {id:2341,person: Bob} 

...和...

  {id:5382,user:Mary} 

...分别。

有没有办法映射personuser字段添加到名称字段中?



(注意:我只需要从JSON字符串转换为Java对象 - 永远不会相反)。

解决方案

2015年10月, Gson 2.4版 changelog )在反序列化时添加了对 @SerializedName 使用替代/多个名称的功能。

用法:

c $ c> @SerializedName(value =name,alternate = {person,user})

https://google.github.io/gson/apidocs/ com / google / gson / annotations / SerializedName.html


Is there any way in Gson to map multiple JSON fields to a single Java object member variable?

Let's say I have a Java class...

public class MyClass {
    String id;
    String name;
}

I want to use this single class with two different services. However, these two services differ in how they return their data...

{ "id": 2341, "person": "Bob" }

... and ...

{ "id": 5382, "user": "Mary" }

... respectively.

Is there any way to map both the "person" and "user" fields in the JSON string to the name field in the Java object?

(Note: I only ever need to convert from JSON string to Java object - never the other way around.)

解决方案

In October 2015, Gson version 2.4 (changelog) added the ability to use alternate/multiple names for @SerializedName when deserializing. No more custom TypeAdapter needed!

Usage:

@SerializedName(value="name", alternate={"person", "user"})

https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html

这篇关于多个GSON @SerializedName每个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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