将两种类型的 json 转换为同一个对象

Convert two type of json to the same object

我正在为 api return json 的 Web 服务编写框架。我使用 Jackson 库反序列化 json 字符串。 api return 属性继续获取请求的结果。像这样的响应:

{
    continueToken:"token",
    results: [ 
                {
                },
             ]
}

所有的回复都是这个结构。唯一的问题是 continue 属性的名称因请求而异。名字是这样的

prefix + "continue"

我只想创建一个 class 并且能够将 json 映射到这个 class。我怎样才能做到这一点?这是我想要的:

public class Response {
    private String continueToken;
    private List<Article> results;

    public Response (String continueToken, Article[] articles) {
         this.continueToken = continueToken;
         this.results = Arrays.asList(articles);
    }
}
//Here the name is ttcontinue
String json = request.get(type1);
Response r = jsonToResponse(json);

//Here the name is llcontinue
json = request.get(type2);
r = jsonToResponse(json);

hm.. 你有一个动态字段名称,注释解决方案无法工作。假设没有其他 JSON 字段以 "continue" 结尾(在您的示例中成立),您可以按照以下步骤操作:

  1. 迭代 JSON 键,如 this post
  2. 使用field.getKey().endsWith("continue")找到你想要的密钥
  3. 使用 this post 中的代码将 JSON 节点中的密钥替换为 "continueToken"
  4. 现在获取您的 Response 对象