【问题标题】:how to use gson 2.0 on - onResponse from Retrofit 2.0如何使用 gson 2.0 on - 来自 Retrofit 2.0 的 onResponse
【发布时间】:2016-05-08 09:34:36
【问题描述】:

我正在使用新的改造 2.0 进行 http 调用, 并获得回调, 我想使用 gson 2.0 库来解析那个 json obj 并能够做到

jsonData.sector[2].sectorOne

这是我的回调:

retrofitApi.Factory.getInstance().getCallData().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                try {

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("myLogs", "failed to Retrive Data");
                Log.d("myLogs", "becouse: "+t);
                largeTextVar.setText("failed: " + t);
            }
        });

这就是我的回调的样子

{
  "data": {
    "sector": [
      [
        {
          "scanned": false,
          "sectorOne": "",
          "sectorTwo": "",
          "sectorThree": ""
        },
        {
          "scanned": false,
          "sectorOne": "",
          "sectorTwo": "",
          "sectorThree": ""
        }
      ]
    ]
  },
  "curserLocation": {
    "elevation": 30,
    "horizontal": 105
  }
}

我正在使用:

compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1' 

我到处寻找如何做到这一点,但我找不到一个简单的解决方案, 实现这一目标的最简单、最简单的方法是什么?

【问题讨论】:

  • 使用 Gson 转换器进行改造不会返回 JSON,它会返回 Java 对象,因此无需像您要求的那样使用 JSON 路径
  • 你如何解析那个对象? (在我的例子中说)@cricket_007
  • @cricket_007 ?你知道如何解析响应吗?类似于 response.body.string 吗?类似的东西?
  • 您不需要将任何内容转换为字符串。我不知道你如何设置改造来处理事情,但也许这会有所帮助guides.codepath.com/android/Consuming-APIs-with-Retrofit
  • 是的,我会调查一下,我只是想访问其中一个变量,例如 do response.body.string[2].. 等等...

标签: android json gson retrofit


【解决方案1】:

好的,我将解释如何将JSON 响应转换为POJO

首先你必须在JSON Schema 2 POJO中创建一个POJO类

  1. 粘贴您的示例 JSON 响应
  2. 选择源类型:JSON
  3. 注解风格:Gson

它会为你生成一个POJO 类。

然后在您的onResponse 方法中:

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if(response.code()==200){
            Gson gson = new GsonBuilder().create();
                YourPOJOClass yourpojo=new YourPOJOClass ();
                try {
                    yourpojo= gson.fromJson(response.body().toString(),YourPOJOClass.class); 
                } catch (IOException e) {
                    // handle failure to read error
                    Log.v("gson error","error when gson process");  
                }
        }

别忘了加compile 'com.google.code.gson:gson:2.4'

另一种方法:像上面那样创建一个 pojo 类。

在您的 API 中:

@POST("endpoint")
public Call<YourPOJOClass> exampleRequest();

调用时:

    OkHttpClient okClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build();

    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .create();

    Retrofit client = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(okClient)
            .build();

    YourApiClass service = client.create(YourApiClass.class);

    Call<YourPOJOClass> call=service.exampleRequest();
    call.enqueue(new Callback<YourPOJOClass>() {
        @Override
        public void onResponse(Call<YourPOJOClass> call, Response<YourPOJOClass> response) {
            //already Gson convertor factory converted your response body to pojo
            response.body().getCurserLocation();
        }

        @Override
        public void onFailure(Call<YourPOJOClass> call, Throwable t) {

        }
    });

【讨论】:

  • 有没有一种方法可以直接访问我从函数获得的响应中的变量?
  • 不,我不知道,我正在使用 pojo 类来获取变量。我知道的正确方法。
  • jsonschema2pojo 在 zip 文件夹中创建 4 个文件,在您使用的示例中,YourPOJOClass yourpojo=new YourPOJOClass (),您指的是 POJO 中的哪个类?你能解释一下答案吗?
  • 看这张照片,看照片中的蓝线。输入您的类名,它只是一个示例,您可以给它一个特定的名称:hizliresim.com/RkW8lR。如果它生成多个类,则将所有类添加到您的项目中。
猜你喜欢
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 1970-01-01
  • 2015-12-13
  • 2016-10-03
  • 2016-02-21
相关资源
最近更新 更多