【问题标题】:Is there any Default json converters while using Retrofit 1.9.0?使用 Retrofit 1.9.0 时是否有任何默认 json 转换器?
【发布时间】:2015-12-08 17:28:47
【问题描述】:

我的问题是,是否有任何默认转换器,而使用Retrofit 1.9 我的 json 响应将是这样的:

{"Result":"1","UserID":"0"}

请建议我如何将parse 这个json 转换成字符串?

这是我的主要活动:

package first.service.precision.servicefirst;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;

import java.io.IOException;

import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

public class MainActivity extends Activity
{
    public EditText password,userName;
    Button login,resister;
    ProgressBar progressbar;
    TextView tv;
    String TAG="Fails";
    String url="http://172.16.7.203/sfAppServices/SF_UserLogin.svc";
    private ModelLogin Result;



    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        password=(EditText) findViewById(R.id.password);

        userName=(EditText) findViewById(R.id.txtEmployeeCode);

        login=(Button) findViewById(R.id.btnsignin);
        userName.setBackgroundResource(R.drawable.colorfoucs);


        //progess_msz.setVisibility(View.GONE);
        ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf=cn.getActiveNetworkInfo();
        if(nf != null && nf.isConnected()==true )
        {
            Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();

        } else {
            showAlertDialog(MainActivity.this,"No Network","Please Check Your Network Connectivity",true);
        }

        final   ConnectionDetector    cd = new ConnectionDetector(getApplicationContext());

        login.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                progressbar = (ProgressBar) findViewById(R.id.progressBar);
                progressbar.setVisibility(View.VISIBLE);
                final String s1 = userName.getText().toString();
                String s2 = password.getText().toString();
                if (s1.equals("")) {
                    userName.setError("Enter Employee Code");
                }
                if (s2.equals("")) {
                    password.setError("Enter Password");

                }
                OkHttpClient client = new OkHttpClient();
                client.interceptors().add(new Interceptor() {
                    @Override
                    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                        Request original = chain.request();

                        // Customize the request
                        Request request = original.newBuilder()
                                .header("Accept", "application/json")
                                .header("Authorization", "auth-token")
                                .method(original.method(), original.body())
                                .build();

                        com.squareup.okhttp.Response response = chain.proceed(request);

                        // Customize or return the response
                        return response;
                    }
                });
                Retrofit retro = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
                RetrofitRest retrofitRest = retro.create(RetrofitRest.class);
                retrofitRest.getResult(s1, s2, new Callback<ModelLogin>() {
                    @Override
                    public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
                        ModelLogin model=new ModelLogin();
                        if(model.getResult().equals("2"))
                        {
                            Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
                            startActivity(intent);
                            Toast.makeText(MainActivity.this, "Welcome" +""+s1, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {

                    }
                });


                        // public void onResponse(ModelLogin modelLogin, Retrofit retrofit)
                        // {


                        // }

                        // @Override
                        // public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
                        //   progressbar.setVisibility(View.INVISIBLE);
                        //    ModelLogin modelLogin1=new ModelLogin();
                        //    modelLogin1.getLoginResult();
                        //   LoginResult loginResult=new LoginResult();
                        ///   loginResult.getResult();
                        //   ModelLogin modelLogin=new ModelLogin();
                        // modelLogin.getLoginResult().getResult();
                        //   if()
                        //   {

                        //      Toast.makeText(getApplicationContext(),"God",Toast.LENGTH_LONG).show();

                        //  }
                        // else {
                        //      Intent intent=new Intent(getApplicationContext(),Main2Activity.class);
                        //       startActivity(intent);
                        //  }
                        //  }
//
                        //  @Override
                        //   public void onResponse(Response<LoginResult> response, Retrofit retrofit) {

                        //   }

                        ////   @Override
                        //   public void onFailure(Throwable t) {
                        //      Toast.makeText(getApplicationContext(),"God",Toast.LENGTH_LONG).show();
                        //   }
                    }
                    //  call.enqueue(new Callback<ModelLogin>() {
                    //     @Override
                    //     public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {


                    //        }


                    //    @Override
                    //    public void onFailure(Throwable t) {
                    //       Log.d(TAG,"Error");
                    //   }
                    //});





        });

    }


    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon


        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Exit")
                .setMessage("Are you sure you want to close this application?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int d) {
                        finish();
                    }

                })
                .setNegativeButton("No", null)
                .show();
    }
}

这是我的界面:

package first.service.precision.servicefirst;

/**
 * Created by 4264 on 23-11-2015.
 */
import retrofit.Callback;
import retrofit.http.POST;
import retrofit.http.Path;

/**
 * Created by 4264 on 03-11-2015.
 */
public interface RetrofitRest {

    @POST("SF_UserLogin.svc/rest/login/{EMPLOYEECODE}/{PASSWORD}")
void getResult(@Path("EMPLOYEECODE") String empcode, @Path("PASSWORD") String passwrd, Callback<ModelLogin> callback);



    // @GET("SF_UserLogin.svc/rest/Msg")
    // Call<ModelLogin>verify(@Body ModelLogin result);
}

这是我的pojo:

package first.service.precision.servicefirst;

/**
 * Created by 4264 on 23-11-2015.
 */
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by 4264 on 13-11-2015.
 */
public  class ModelLogin
{

    @SerializedName("Result")

    private String Result;
    @SerializedName("UserID")
    @Expose
    private Integer UserID;
    @SerializedName("ModuleID")
    @Expose
    private Integer ModuleID;
    @SerializedName("ModuleName")
    @Expose
    private String ModuleName;

    /**
     *
     * @return
     * The Result
     */
    public String getResult() {
        return Result;
    }

    /**
     *
     * @param Result
     * The Result
     */
    public void setResult(String Result) {
        this.Result = Result;
    }

    /**
     *
     * @return
     * The UserID
     */
    public Integer getUserID() {
        return UserID;
    }

    /**
     *
     * @param UserID
     * The UserID
     */
    public void setUserID(Integer UserID) {
        this.UserID = UserID;
    }

    /**
     *
     * @return
     * The ModuleID
     */
    public Integer getModuleID() {
        return ModuleID;
    }

    /**
     *
     * @param ModuleID
     * The ModuleID
     */
    public void setModuleID(Integer ModuleID) {
        this.ModuleID = ModuleID;
    }

    /**
     *
     * @return
     * The ModuleName
     */
    public String getModuleName() {
        return ModuleName;
    }

    /**
     *
     * @param ModuleName
     * The ModuleName
     */
    public void setModuleName(String ModuleName) {
        this.ModuleName = ModuleName;
    }

}

我的错误信息:

我正在尝试使用稳定的改造 1.9 制作登录页面,但是当我尝试运行它时,它会引发方法错误,到目前为止我尝试的是

这是我的主要活动:

package first.service.precision.servicefirst;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

public class MainActivity extends Activity
{
    public EditText password,userName;
    Button login,resister;
    ProgressBar progressbar;
    TextView tv;
    String TAG="Fails";
    String url="http://172.16.7.203/sfAppServices/SF_UserLogin.svc";
    private ModelLogin Result;



    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        password=(EditText) findViewById(R.id.password);

        userName=(EditText) findViewById(R.id.txtEmployeeCode);

        login=(Button) findViewById(R.id.btnsignin);
        userName.setBackgroundResource(R.drawable.colorfoucs);


        //progess_msz.setVisibility(View.GONE);
        ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf=cn.getActiveNetworkInfo();
        if(nf != null && nf.isConnected()==true )
        {
            Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();

        } else {
            showAlertDialog(MainActivity.this,"No Network","Please Check Your Network Connectivity",true);
        }

        final   ConnectionDetector    cd = new ConnectionDetector(getApplicationContext());

        login.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                progressbar = (ProgressBar) findViewById(R.id.progressBar);
                progressbar.setVisibility(View.VISIBLE);
                final String s1 = userName.getText().toString();
                String s2 = password.getText().toString();
                if (s1.equals("")) {
                    userName.setError("Enter Employee Code");
                }
                if (s2.equals("")) {
                    password.setError("Enter Password");

                }

                Retrofit retro = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
                RetrofitRest retrofitRest = retro.create(RetrofitRest.class);
                retrofitRest.getResult(s1, s2, new Callback<ModelLogin>() {
                    @Override
                    public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
                        if(response.isSuccess()){
                            Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
                            startActivity(intent);
                            Toast.makeText(MainActivity.this, "Welcome" +""+s1, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {

                    }
                });


                        // public void onResponse(ModelLogin modelLogin, Retrofit retrofit)
                        // {


                        // }

                        // @Override
                        // public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
                        //   progressbar.setVisibility(View.INVISIBLE);
                        //    ModelLogin modelLogin1=new ModelLogin();
                        //    modelLogin1.getLoginResult();
                        //   LoginResult loginResult=new LoginResult();
                        ///   loginResult.getResult();
                        //   ModelLogin modelLogin=new ModelLogin();
                        // modelLogin.getLoginResult().getResult();
                        //   if()
                        //   {

                        //      Toast.makeText(getApplicationContext(),"God",Toast.LENGTH_LONG).show();

                        //  }
                        // else {
                        //      Intent intent=new Intent(getApplicationContext(),Main2Activity.class);
                        //       startActivity(intent);
                        //  }
                        //  }
//
                        //  @Override
                        //   public void onResponse(Response<LoginResult> response, Retrofit retrofit) {

                        //   }

                        ////   @Override
                        //   public void onFailure(Throwable t) {
                        //      Toast.makeText(getApplicationContext(),"God",Toast.LENGTH_LONG).show();
                        //   }
                    }
                    //  call.enqueue(new Callback<ModelLogin>() {
                    //     @Override
                    //     public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {


                    //        }


                    //    @Override
                    //    public void onFailure(Throwable t) {
                    //       Log.d(TAG,"Error");
                    //   }
                    //});





        });

    }


    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon


        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Exit")
                .setMessage("Are you sure you want to close this application?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int d) {
                        finish();
                    }

                })
                .setNegativeButton("No", null)
                .show();
    }
}

这是我的pojo:

package first.service.precision.servicefirst;

/**
 * Created by 4264 on 23-11-2015.
 */
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by 4264 on 13-11-2015.
 */
public  class ModelLogin
{

    @SerializedName("Result")

    private String Result;
    @SerializedName("UserID")
    @Expose
    private Integer UserID;
    @SerializedName("ModuleID")
    @Expose
    private Integer ModuleID;
    @SerializedName("ModuleName")
    @Expose
    private String ModuleName;

    /**
     *
     * @return
     * The Result
     */
    public String getResult() {
        return Result;
    }

    /**
     *
     * @param Result
     * The Result
     */
    public void setResult(String Result) {
        this.Result = Result;
    }

    /**
     *
     * @return
     * The UserID
     */
    public Integer getUserID() {
        return UserID;
    }

    /**
     *
     * @param UserID
     * The UserID
     */
    public void setUserID(Integer UserID) {
        this.UserID = UserID;
    }

    /**
     *
     * @return
     * The ModuleID
     */
    public Integer getModuleID() {
        return ModuleID;
    }

    /**
     *
     * @param ModuleID
     * The ModuleID
     */
    public void setModuleID(Integer ModuleID) {
        this.ModuleID = ModuleID;
    }

    /**
     *
     * @return
     * The ModuleName
     */
    public String getModuleName() {
        return ModuleName;
    }

    /**
     *
     * @param ModuleName
     * The ModuleName
     */
    public void setModuleName(String ModuleName) {
        this.ModuleName = ModuleName;
    }

}

这是我的构建 gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "first.service.precision.servicefirst"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug{
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
        }

    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:23.0.1'
        compile 'com.squareup.retrofit:retrofit:1.9.0'

        compile 'com.squareup.okhttp:okhttp:2.4.0'
        compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
        compile 'org.parceler:parceler:0.2.13'
        compile 'com.squareup:otto:1.3.8'
    }
}

还有我的 logcat 错误信息:

2-08 10:27:58.602  11156-11156/first.service.precision.servicefirst E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IllegalArgumentException: Unable to create call adapter for class first.service.precision.servicefirst.ModelLogin
    for method RetrofitRest.getResult
            at retrofit.Utils.methodError(Utils.java:177)
            at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:47)
            at retrofit.MethodHandler.create(MethodHandler.java:26)
            at retrofit.Retrofit.loadMethodHandler(Retrofit.java:151)
            at retrofit.Retrofit$1.invoke(Retrofit.java:132)
            at $Proxy0.getResult(Native Method)
            at first.service.precision.servicefirst.MainActivity$1.onClick(MainActivity.java:76)
            at android.view.View.performClick(View.java:4275)
            at android.view.View$PerformClick.run(View.java:17434)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:177)
            at android.app.ActivityThread.main(ActivityThread.java:4947)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class first.service.precision.servicefirst.ModelLogin. Tried:
    * retrofit.ExecutorCallAdapterFactory
            at retrofit.Retrofit.nextCallAdapter(Retrofit.java:207)
            at retrofit.Retrofit.callAdapter(Retrofit.java:175)
            at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:45)
            ... 16 more

这是我的成绩:

    apply plugin: 'com.android.application'

    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.1"

        defaultConfig {
            applicationId "first.service.precision.servicefirst"
            minSdkVersion 15
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
            debug{
                debuggable true
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
            }

        }

        dependencies {
            compile fileTree(dir: 'libs', include: ['*.jar'])
            compile 'com.android.support:appcompat-v7:23.0.1'
            compile 'com.squareup.retrofit:retrofit:1.9.0'
            compile 'com.squareup.retrofit:converter-jackson:1.9.0'
            compile 'com.squareup.okhttp:okhttp:2.4.0'
            compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
            compile 'org.parceler:parceler:0.2.13'
            compile 'com.squareup:otto:1.3.8'
        }

}

【问题讨论】:

  • 这是一种登录活动,如果结果响应为 1,它将重定向到下一个活动

标签: android json retrofit


【解决方案1】:

您必须为您的响应创建一个 Bean 对象。例如

 public class LoginResponse {
   public String Result;
   public String UserId
 }

并让该端点的 Retrofit 休息接口/描述符返回 LoginResponse。该对象的一个​​实例将作为CallBack (Callback&lt;LoginResponse&gt;) 的一部分返回。当success 被调用时,检查Result 的值并采取相应的行动

【讨论】:

  • 是的,我做了同样的事情,但它的服务不能无效
  • 您发布的代码中有很多混乱。如果您使用的是改造 1.9,那么您应该使用 RestAdapter.Builder 而不是 Retrofit.Builder。 Second Retrofit 1.9 不需要 Gson 作为外部依赖(去掉com.squareup.retrofit:converter-gson:2.0.0-beta2)。第三,您发布了两个版本的 RestInterace
  • 对不起,我删除了一个接口,好的,我将删除 gson 转换器
  • 在我从依赖项改造中删除该 gson 后无法解决
  • 您是否遇到编译时错误?你还在用Retrofit.Builder吗?
猜你喜欢
  • 2017-02-05
  • 2014-03-01
  • 1970-01-01
  • 2017-09-27
  • 2015-08-26
  • 1970-01-01
  • 2012-10-08
  • 2019-11-26
相关资源
最近更新 更多