Gson Property Order In Android
I have integrated Gson to create the json used in a request for an android application. Here is my model class public class TwitterUser { @Expose public String gid; public String
Solution 1:
Gson doesn't support definition of property order out of the box, but there are other libraries that do. Jackson allows defining this with @JsonPropertyOrder
, for example.
But of course Gson has it's way so you can do it by creating your very own Json serializer:
publicclassTwitterUserSerializerimplementsJsonSerializer<TwitterUser> {
@OverridepublicJsonElementserialize(TwitterUser twitterUser, Type type, JsonSerializationContext context) {
JsonObjectobject = newJsonObject();
object.add("gid", context.serialize(twitterUser.getGid());
object.add("displayName", context.serialize(twitterUser.getDisplayName());
// ...returnobject;
}
}
Then of course you need to pass this serializer to Gson during Setup like this:
Gsongson=newGsonBuilder().registerTypeAdapter(TwitterUser.class, newTwitterUserSerializer()).excludeFieldsWithoutExposeAnnotation().create();
Stringjson= gson.toJson(twitterUser);
Post a Comment for "Gson Property Order In Android"