我有以下問題。java jackson解析包含泛型類型對象的對象
我必須解析一個json請求到一個包含泛型類型字段的對象中。
編輯
我已經使用普通類類型(所以我做之前,我與一般的更換它的工作)的一些測試。現在解析單個元素的效果很好。
問題是當我需要解析出一個列表對象的類。
所以我必須以某種方式通知傑克遜,我的T是類型列表而不是僅僅是AlbumModel。
這是我試過的。
@Override
public ListResponseModel<AlbumModel> parse(String responseBody) throws Exception {
JavaType type = mapper.getTypeFactory().constructParametricType(ResponseModel.class,
AlbumModel.class);
return mapper.readValue(responseBody,
mapper.getTypeFactory().constructParametricType(ResponseModel.class, type));
}
但上面的代碼不起作用。什麼是這樣的解決方案?
我在ListResponseModel泛型類型的定義如下:List<T> data
成功,如:
public class BaseResponseModel<T> {
@JsonProperty("data")
private T data;
@JsonProperty("paginations")
private PaginationModel pagination;
}
到目前爲止,我有以下的代碼,但它始終解析到一個哈希。
public class ResponseParser extends BaseJacksonMapperResponseParser<ResponseModel<AlbumModel>> {
public static final String TAG = ResponseParser.class.getSimpleName();
@Override
public ResponseModel<AlbumModel> parse(String responseBody) throws Exception {
return mapper.readValue(responseBody,
mapper.getTypeFactory().constructParametricType(ResponseModel.class, AlbumModel.class));
}
}
public abstract class BaseJacksonMapperResponseParser<T> implements HttpResponseParser<T> {
public static final String TAG = BaseJacksonMapperResponseParser.class.getSimpleName();
public static ObjectMapper mapper = new ObjectMapper();
static {
mapper.disable(Feature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
}
}
好吧,我開始得到這個..我做了這個工作使用一個單一的對象,但我無法做它的列表。你能提供更多的信息嗎?感謝您迄今爲止的努力。 – DArkO
查看更新 - 嘗試使用更一般的Collection類。 –
好吧,我已經做到了。與此類似,但你證明了一點。非常感謝。唯一我討厭的是我必須發送.class,並且定義泛型參數,並且最終得到類似於新分析器(AlbumModel.class) –
DArkO