Gson property order in android

天涯浪子 提交于 2021-01-27 07:11:18

问题


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 icon_url;
public Boolean is_app_user;
@Expose
public String displayName;

public TwitterUser(String l, String i, String url, Boolean app_user) {
    gid = i;
    displayName = l;
    icon_url = url;
    is_app_user = app_user;
}

public TwitterUser(String l, String i) {
    gid = i;
    displayName = l;
}

public String getGid() {
    return gid;
}

public void setGid(String gid) {
    this.gid = gid;
}

public String getIcon_url() {
    return icon_url;
}

public void setIcon_url(String icon_url) {
    this.icon_url = icon_url;
}

public Boolean getIs_app_user() {
    return is_app_user;
}

public void setIs_app_user(Boolean is_app_user) {
    this.is_app_user = is_app_user;
}

public String getDisplayName() {
    return displayName;
}

public void setDisplayName(String displayName) {
    this.displayName = displayName;
}

Here is how i create the json request

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();              
gson.toJson(twitterUser));

But when I send the request to the server - the order will be rejected. I have to change the request's field order to stay:

  1. gid
  2. displayName

but gson creates other way around, is there any way to achieve this.


回答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:

public class TwitterUserSerializer implements JsonSerializer<TwitterUser> {

    @Override
    public JsonElement serialize(TwitterUser twitterUser, Type type, JsonSerializationContext context) {
        JsonObject object = new JsonObject();
        object.add("gid", context.serialize(twitterUser.getGid());
        object.add("displayName", context.serialize(twitterUser.getDisplayName());
        // ...
        return object;
    }
}

Then of course you need to pass this serializer to Gson during Setup like this:

Gson gson = new GsonBuilder().registerTypeAdapter(TwitterUser.class, new TwitterUserSerializer()).excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(twitterUser);

See also:

  • Gson User Guide - Custom serializers and deserializers


来源:https://stackoverflow.com/questions/24860255/gson-property-order-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!