Guest User

Untitled

a guest
Apr 22nd, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. public class GsonConvert implements Converter {
  2. private static final Gson GSON = new Gson();
  3.  
  4. @Override
  5. public <S, F> SimpleResponse<S, F> convert(Type succeed, Type failed, Response response,
  6. boolean fromCache) throws Exception {
  7.  
  8. S succeedData = null;
  9. F failedData = null;
  10. String JSON = response.body().string();
  11. JSON = Net.decrypt(JSON);
  12.  
  13. if (Net.printResponse) {
  14. LogCat.r("JSON", JSON);
  15. } else {
  16. LogCat.json("响应体", JSON);
  17. }
  18.  
  19. int code = response.code();
  20.  
  21. // 解析服务器错误码
  22. if (code >= 200 && code < 300) {
  23. JSONObject jsonObject = null;
  24. try {
  25. jsonObject = new JSONObject(JSON);
  26. } catch (JSONException e) {
  27. e.printStackTrace();
  28. failedData = (F) "无法解析错误信息";
  29. }
  30.  
  31. // 解析后台自定义错误码
  32. int customCode = jsonObject.optInt("code");
  33. if (customCode == 1) {
  34. {
  35. try {
  36. succeedData = GSON.fromJson(JSON, succeed);
  37. } catch (JsonSyntaxException e) {
  38. e.printStackTrace();
  39. failedData = (F) "无法解析数据";
  40. }
  41. }
  42. } else {
  43. failedData = (F) jsonObject.optString("msg");
  44. code = customCode;
  45. }
  46.  
  47. } else if (code >= 400 && code < 500) {
  48. failedData = (F) "发生异常错误";
  49. } else if (code >= 500) {
  50. failedData = (F) "服务器开小差啦";
  51. }
  52.  
  53. return SimpleResponse.<S, F>newBuilder()
  54. .code(code)
  55. .headers(response.headers())
  56. .fromCache(fromCache)
  57. .succeed(succeedData)
  58. .failed(failedData)
  59. .build();
  60. }
  61. }
Add Comment
Please, Sign In to add comment