【问题标题】:Nested JSON Object (Retrofit)嵌套 JSON 对象(改造)
【发布时间】:2015-07-05 09:53:08
【问题描述】:

我正在使用 Retrofit 发送图片请求并接收这个 Json

{"response":{
    "face":{
        "value":"true",
        "confidence":55
    },
    "gender":{
        "value":"male",
        "confidence":73
    },
    ...
}}

我收到了 Retrofit....

   RestAdapter adapter = new RestAdapter.Builder()
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setEndpoint(END_POINT)
                    .build();
   Mylistenerr listener = adapter.create(Mylistenerr.class);
   File photo = new File(picturePath);
   TypedFile image = new TypedFile("multipart/image/jpg", photo);
   listener.setUserImage(
       image,
       new Callback<respostring>() {
           @Override
           public void success(respostring rp, Response arg1) {}

          @Override
          public void failure(RetrofitError arg0) {
             pd.hide();
             pd.dismiss();
             Log.d("ERROR:", arg0.getLocalizedMessage());
          }
      });     
    }

    private static class respostring {
       private Content face;
       private Content gender;
           respostring() {}
    }


   class Content
   { 
      private int confidence;
      private String value;

      Content(){}

      public int getconf(){
        return this.confidence;
      }
      public String getvalue(){
        return this.value;
      }
}

我的界面

public interface Mylistenerr {
  @Multipart
  @POST("/public/test")
  void setUserImage(
     @Part("image") TypedFile file,          
     Callback<respostring> response);
}

但存在改造错误。这里有什么我想念的吗?

【问题讨论】:

  • 在回调 响应中是“respostring”); ??

标签: java android json retrofit


【解决方案1】:

我建议您使用 Gson 进行 json 反序列化,因为改造非常支持它。然后你可以像这样创建类:

你的脸类:

public class Face implements Serializable {

    @SerializedName("value")
    public boolean value;

    @SerializedName("confidence")
    public int confidence;

}

你的性别等级:

public class Gender implements Serializable {

    @SerializedName("value")
    public String value;

    @SerializedName("confidence")
    public int confidence;

}

你的响应类:

public class YourResponseType implements Serializable {

    @SerializedName("face")
    public Face face;

    @SerializedName("gender")
    public Gender gender;
}

那么您实际上可以让改造为您完成剩下的工作:

listener.setUserImage(image, new Callback<YourResonseType>() {...});

希望有帮助!

【讨论】:

  • 对不起,我忘了添加一个包装响应的类。类似于 public class MyResponseContainer implements Serializable { @SerializedName("response") YourResponseType yourResponse; }
  • 是的,它不见了,我后来才发现,我打算来写它……但你确实找到了,非常感谢:)
猜你喜欢
  • 2021-03-12
  • 2018-09-23
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 2019-05-12
  • 2014-05-29
  • 2016-07-07
相关资源
最近更新 更多