Gson用不同的数据解析相同的密钥

时间:2018-02-15 09:27:44

标签: android gson

我如何解析服务器收到的包含密钥不同值的数据?

{ "location":[{"id":"1"},{"id":"2"}]}

{"location":{"id":"1"}}

不确定如何处理以下对象:

   public class UserLocation {
    @SerializedName("location")
    List<String> location; / String location;

   @SerializedName("name")
    String name;
}

在第一个请求中,我确实获得了数组格式,在第二个请求中,我从服务器获取字符串格式。

2 个答案:

答案 0 :(得分:5)

你必须像这样使用自定义反序列化:

JsonDeserializer<UserLocation> deserializer = new JsonDeserializer<UserLocation>() {
                @Override
                public UserLocation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                    List<String> location  = new ArrayList<>();
                    if(json.isJsonArray()){
                        JsonArray jsonArray = json.getAsJsonArray();

                        for (JsonElement jsonElement : jsonArray) {
                            location.add(jsonElement.getAsString());
                        }

                    }else{
                        location.add(json.getAsString());
                    }
                    return  new UserLocation(location);
                }
            };

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(UserLocation.class, deserializer);
Gson customGson = gsonBuilder.create();
UserLocation object = customGson.fromJson(jsoninput, UserLocation.class);

查看此link了解详情

答案 1 :(得分:-1)

创建一个同时具有位置和位置列表的类,然后序列化该类对象,参见下面的示例。

<强> UserLocation.java

public class UserLocation{

@SerializedName("location")
@Expose
private MyLocation myLocation;

}

<强> MyLocation.java

public class MyLocation{


private List<Location> locationList = null;


private Location location;

}

<强> Location.java

public class Location {

 @SerializedName("id")
 @Expose
 private String id;

 public String getId() {
 return id;
}

 public void setId(String id) {
 this.id = id;
}

 }