简体   繁体   中英

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. 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 .

So you cannot not pass the JSON in your question and expect it to be de-serialized as an instance of Errors . Instead you need some DTO that matches to your JSON response string. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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