简体   繁体   English

如何使用GSON解析错误?

[英]How can I parse errors using GSON?

My response is: 我的回答是:

{
    "data":[],
    "meta":[],
    "errors":[["invalid credentials"]]
}   

I am not able to de-serialize it by below method: 我无法通过以下方法将其反序列化:

Errors errors = gson.fromJson(response, new TypeToken<Errors>(){}.getType());

Errors 失误

public class Errors {
    private HashMap<String, Object> errors;

    public HashMap<String, Object> getErrors() {
        return errors;
    }
}

How to de-serialize errors correctly? 如何正确反序列化错误?

试试这个代码

    Errors errors=new Gson().fromJson("here your error data",Errors.class);

In your example Errors is not Hashmap, it is an array of arrays. 在您的示例中, Errors不是Hashmap,它是一个数组数组。 Change the class to this and see whether it works or not. 将类更改为此,然后查看它是否起作用。

public class Errors {

  private List<List<String>> errors;

  public List<List<String>> getErrors() {
     return errors;
  }

}

You are de-serializing - not errors - but a response having these errors. 您正在反序列化-不是错误-而是包含这些错误的响应。 There JSON presents an object say Response that contains data , meta & errors . JSON中提供了一个名为Response的对象,其中包含datameta dataerrors

So you cannot not pass the JSON in your question and expect it to be de-serialized as an instance of Errors . 因此,您不能在问题中传递JSON并期望将其反序列化为Errors的实例。 Instead you need some DTO that matches to your JSON response string. 相反,您需要一些与您的JSON响应字符串匹配的DTO。 It could be like: 可能是这样的:

@Getter @Setter
public class Response {
    // You can comment/remove data & meta
    // if you do not need then
    private List<?> data;
    private List<?> meta;
    private List<List<String>> errors;
}

De-serialize like: 像这样反序列化:

Response res = new Gson().fromJson(YOUR_JSON, Response.class);

and get errors like: 并得到如下错误:

res.getErrors();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM