Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

java - Multiple GSON @SerializedName per field?

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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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://www.javadoc.io/doc/com.google.code.gson/gson/2.6.2/com/google/gson/annotations/SerializedName.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...