使用Retrofit 2.0时如何将Json结果转换为Object

时间:2017-08-28 07:14:46

标签: java android json gson retrofit

这是我的Json结果代码:

      {
    "head": {
      "rspCode": 0,
      "rspMsg": "成功",
      "dataVersion": "",
      "appVersion": "",
      "deployVersion": "",
      "msgCount": ""
    },
    "body": {
      "orderNo": 166,
      "orderTime": "2017-07-27 09:30:48",
      "orderStatus": "Pending",
      "productsPart": [
        {
          "name": "iPhone",
          "total": 101,
          "orderProtList": [
            {
              "productSkuPrice": "101.0000",
              "productQuantity": "1",
              "productSku": "quantity"
            }
          ]
        }
      ]
    }
    }

这是我的实体代码,我正在使用改造来重建我的代码结构,但转换json难倒我:

public class ResponseObj<T> {
private RespHeader head;
private T body;
........
(get set methods ignored)
}

RespHead.java:

public class RespHeader {
private String dataVersion;
private String appVersion;
private String deployVersion;
private String msgCount;
private int rspCode; //响应码
private String rspMsg;
.....
  (get set methods ignored)
 }

这是Body Class Content:

private int orderNo;
private String orderTime;
private String orderStatus;
private List<ProductsPartBean> productsPart;
...... 
(get set ignored)

我尝试使用define custom GsonConverter来转换此JSON文本。 以下是我的步骤:

public class GsonResponseConverter extends Converter.Factory {
private Gson gson;

public GsonResponseConverter(Gson gson) {
    this.gson = gson;
}


public static GsonResponseConverter create() {
    return create(new Gson());
}

@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static GsonResponseConverter create(Gson gson) {
    if (gson == null) throw new NullPointerException("gson == null");
    return new GsonResponseConverter(gson);
}


@Nullable
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    TypeAdapter<?> adapter = this.gson.getAdapter(TypeToken.get(type));
    return new CustomResponseConverter<>(this.gson);
}

@Nullable
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}

@Nullable
@Override
public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    return super.stringConverter(type, annotations, retrofit);
}

private static class CustomResponseConverter<T> implements Converter<ResponseBody, ResponseObj<T>> {
    Gson gson;
    public CustomResponseConverter(Gson gson) {
        this.gson = gson;
    }
    @Override
    public ResponseObj<T> convert(ResponseBody value) throws IOException {
        String valueString = value.string();
        JSONObject obj = null;
        ResponseObj<T> resp = new ResponseObj();
        try {
            obj = new JSONObject(valueString);
            if (obj.has("head")) {
                JSONObject obj_head = obj.getJSONObject("head");
                resp.setHead(gson.fromJson(obj_head.toString(), RespHeader.class));
            }
            if (obj.has("body")) {
                JSONObject obj_body = obj.optJSONObject("body");
                if (!InputHelper.isEmpty(obj_body) && obj_body.length() > 0) {
                    resp.setBody(gson.fromJson(obj_body.toString(), (Type) resp.getBody().getClass()));
                } else {
                    resp.setBody(null);
                }
            }
        } catch (JSONException e) {
            Logger.e(e.getMessage());
            RespHeader header = new RespHeader();
            header.setRspCode(001);
            header.setRspMsg("server response error");
            resp.setHead(header);
            resp.setBody(null);
        }
        return resp;
    }
}
 }

我的通用不起作用,因为我初始化一个null ResponseObj,我的身体通用没有传入,我该怎么做才能解决这个问题,使用它的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

看这里......

resp.setBody(gson.fromJson(obj_body.toString(), (Type) resp.getBody().getClass()));

你在同一条线上叫一个吸气剂和二传手。除非先前设置(它看起来不像),否则getter将始终返回null。

我的建议是这样的

public class ResponseObj<T> {
    private RespHeader head;
    private T body;

    public Type getType() {
        // TODO
    }
}

resp.getType()不依赖于Body(因为对象内容/引用是一个单独的变量而不是代表它的Class

值得一提的是:你无法获得通用的类... How to get a class instance of generics type T

答案 1 :(得分:0)

1)您可以使用Gson Converter for Retrofit 2

2)然后创建POJO对象。您可以使用this tool。检查源类型:JSON和注释样式:Gson

3)使用Retrofit 2创建您的请求,并使用您的POJO对象进行服务器响应。

4)利润!