如何使用改造 2.0 解析 json? [英] How to parse a json using retrofit 2.0?

查看:47
本文介绍了如何使用改造 2.0 解析 json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用改造解析 json 对象有疑问我的 json 响应将是这样的:

Am having a doubt on parsing json objects using retrofit my json response will be like this:

{"loginResult":"{\"Result\":2,\"UserID\":0,\"ModuleID\":1,\"ModuleName\":\"CRM\"}"}

{"loginResult":"{\"Result\":2,\"UserID\":0,\"ModuleID\":1,\"ModuleName\":\"CRM\"}"}

我的疑问是如果响应的结果是 2 它应该重定向到下一页.如何为这个 json 响应创建 pojo?

My doubt is if result from response is 2 it should redirect to next page . How to create pojo for this json response ?

推荐答案

简单的,使用GsonConverterFactory,在使用前你需要把它添加到你的gradle文件中:

Simply,use GsonConverterFactory, before use that you need add this to your gradle file:

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

假设您有一个名为 LoginResponse 的对象,它有一个名为 loginResult 的属性:

Let's say you have a Object called LoginResponse and it has a attribute called loginResult:

public class LoginResponse{
    LoginResult loginResult;
}

LoginResult 对象定义如下:

public class LoginResult{
    int result;
    long userId;
    ...
}

然后使用Retrofit来请求:

    public interface APIService {
        @POST("SOMETHING/login")
        Call<LoginResponse> doLogin();

    }

    public void doSomething() {
        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("YOUR LOGIN BASE URL")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

        APIService service = retrofit.create(APIService.class);
        Call<LoginResponse> loginCall = service.doLogin();
        //if you want to request synchronous:
        LoginResponse response = loginCall.execute();
        //if you want to request asynchronous:
        LoginResponse response = loginCall.enqueue(new Callback<LoginResponse>() {
          @Override void onResponse(/* ... */) {
               // ...
           }

          @Override void onFailure(Throwable t) {
             // ...
          }
        });
    }

当您获得 LoginResponse 后,您就可以开始工作了:

When you get the LoginResponse, you can do you work:

if(response.loginResult.result == 2){
    //do work here.something like startActivity(...);
}

参考:

  1. https://realm.io/news/droidcon-jake-wharton-simple-http-retrofit-2/
  2. http://inthecheesefactory.com/blog/retrofit-2.0/en

这篇关于如何使用改造 2.0 解析 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆