0

I use a REST service that responds in json with messages like this:

{
   "statusMessage":{
      "message":"my message",
      "error":false
   },
   "data":null
}

Field data is an array, sometimes null, sometimes fill with instances of one class (like Partner, Department, Building,... only one type of them).

In my Java app, I have a ServerResponse class and it looks like:

public class ServerResponse {

    private StatusMessage statusMessage;
    private List<Object> data;

    public ServerResponse(StatusMessage statusMessage, List<Object> data) {
        this.statusMessage = statusMessage;
        this.data = data;
    }
    ...
}

When data is null, there is no problem, but when it fills with some objects, I don't know how to deserialize it. If I use:

response = gson.fromJson(result, ServerResponse.class);

I can't cast or use the list of objects in data. Furthermore, if I declare the field data in Java like this:

private List<Department> data;

It works fine with Department type, but, as might be expected, throws error with others types. I'm stuck...

4

1 回答 1

0

如果您不指定类型data,即您List<Object>现在使用,您将至少获得一个地图列表(并且地图可以再次包含列表或地图,具体取决于内容)。

如果您可以通过内容来区分对象的类型,您可以编写一个简单的自定义反序列化器,就像在这里询问的那样(检查isA字段)

于 2013-11-09T22:36:10.350 回答