gpt4 book ai didi

java - 如何将 Jackson 与嵌套泛型一起使用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:52:40 50 4
gpt4 key购买 nike

我用的是 Retrofit 和 Jackson。有一个 POJO 是这样的:

public class QuotationHttpResult<T> {
private int code;
private Result result;

public T getData(){
return result == null ? null : result.getData();
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public Result getResult() {
return result;
}

public void setResult(Result result) {
this.result = result;
}

class Result{
private T data;

public T getData() {
return data;
}
}
}

归档的数据就是我需要的,有时是一个POJO,有时是一个List。当它是一个列表时,即使我使用 TypeReference,jackson 也只是将数据转换为 LinkedHashMap:Json 字符串是:

 {"code": 0,
"result": {
"data": [
{
"id": "1000",
"name": "tecent"
},
{
"id": "1001",
"name": "alibaba"
}
]
}
}

转换代码:

ObjectMapper mapper = new ObjectMapper();
QuotationHttpResult<List<MyClass>> result = mapper.readValue(json,new TypeReference<QuotationHttpResult<List<MyClass>>>() {});

MyClass 很简单:

class MyClass{
String id;
String name;
}

我看到这个问题,How to use Jackson with Generics , 当我不嵌套泛型时一切顺利,但是当嵌套泛型时我该怎么办?

最佳答案

首先你应该制作Result静态 ( more info ) 或将其移出 QuotationHttpResult ,所以 jackson 可以看到它 data类型。因此,您必须将其设为通用 Result<T> .您还必须将 getter 和 setter 添加到您的 MyClass POJO 或为 jackson 添加注解。

这是演示:

public class QuotationHttpResult<T> {
private int code;

private Result<T> result;

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public Result<T> getResult() {
return result;
}

public void setResult(Result<T> result) {
this.result = result;
}

public static class Result<T>{
private T data;

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}
}
}

public class MyClass {
private String id;
private String name;

public String getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

public static void main(String[] args) throws IOException {
String json = " {\"code\": 0,\n" +
" \"result\": {\n" +
" \"data\": [\n" +
" {\n" +
" \"id\": \"1000\",\n" +
" \"name\": \"tecent\"\n" +
" }, \n" +
" {\n" +
" \"id\": \"1001\",\n" +
" \"name\": \"alibaba\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }";
ObjectMapper mapper = new ObjectMapper();
QuotationHttpResult<MyClass> result = mapper.readValue(json,new TypeReference<QuotationHttpResult<List<MyClass>>>() {});
System.out.println(result);
}

关于java - 如何将 Jackson 与嵌套泛型一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37044721/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com