这是我的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)
 }


这是身体类别的内容:

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


我尝试使用定义自定义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;
    }
}
 }


我的仿制药不起作用,因为我初始化了一个空的ResponseObj,而我的身体仿制药没有传入,我该如何解决这个问题,正确的使用方法是什么?

最佳答案

看这里...

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


您在同一行上调用一个getter和setter。除非事先设置(看起来不是这样),否则getter将始终返回null。

我的建议是这样的

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

    public Type getType() {
        // TODO
    }
}


resp.getType()不依赖主体的情况下(因为对象内容/引用是一个独立的变量,而不是表示它的Class

值得一提的是:您无法获得泛型类... How to get a class instance of generics type T

10-08 15:06