如何在android中处理改装响应Kotlin?

时间:2018-01-28 09:42:42

标签: android api kotlin retrofit

大家。 我正在使用改造从api调用做示例Android Kotlin项目。我调用了api并显示响应logcat。但它不是从服务器处理用户ID和数据。所以,如果你知道Guys分享你最好的经历。

  val params = HashMap<String, String>()
    params["api_key"] = "api_key_value"
    params["username"] = "abcd"
    params["password"] = "1234"

    doApiLogin.getLogin(params).enqueue(object : Callback<GetLoginAndRegisterResp> {

        override fun onResponse(call: Call<GetLoginAndRegisterResp>?, response: Response<GetLoginAndRegisterResp>?) {
            //To change body of created functions use File | Settings | File Templates.
            if (response != null && response.isSuccessful) {

                val getLoginAndRegisterResp = response.body()
                if (getLoginAndRegisterResp != null) {

                    // Here. server response

                } else {

                    val statusCode = response.code()
                    NajibApplication.instance.setLog("statusCode:" + statusCode)
                }


            } else {
                NajibApplication.instance.setLog("onFailure>>>>")
            }
        }

        override fun onFailure(call: Call<GetLoginAndRegisterResp>?, t: Throwable?) {
            //To change body of created functions use File | Settings | File Templates.
            NajibApplication.instance.setLog("onFailure>>>>")
        }

    })

这是Model Class

class GetLoginAndRegisterResp {

data class LoginResp(
        val user_info: UserInfo = UserInfo(),
        val status: Status = Status()

) {
    override fun toString(): String {
        return "LoginResp(user_info=$user_info, status=$status)"
    }
}

data class UserInfo(
        @SerializedName("user_id")
        val user_id: String = "", //

        @SerializedName("username")
        val username: String = "", //abcd

        @SerializedName("login_hash")
        val login_hash: String = "", //

        @SerializedName("facebook_id")
        val facebook_id: String = "",

        @SerializedName("twitter_id")
        val twitter_id: String = "",

        @SerializedName("full_name")
        val full_name: String = "", //

        @SerializedName("thumb_url")
        val thumb_url: String = "",

        @SerializedName("photo_url")
        val photo_url: String = "",

        @SerializedName("mobile")
        val mobile: String = "", //

        @SerializedName("email")
        val email: String = "" //
) {
    override fun toString(): String {
        return "UserInfo(user_id='$user_id', username='$username', login_hash='$login_hash', facebook_id='$facebook_id', twitter_id='$twitter_id', full_name='$full_name', thumb_url='$thumb_url', photo_url='$photo_url', mobile='$mobile', email='$email')"
    }
}

data class Status(
        @SerializedName("status_code")
        val status_code: String = "", //-1

        @SerializedName("status_text")
        val status_text: String = "" //Success.
) {
    override fun toString(): String {
        return "Status(status_code='$status_code', status_text='$status_text')"
    }
}

}

这是Api调用改装Kotlin的代码。

2 个答案:

答案 0 :(得分:1)

import com.google.gson.GsonBuilder

import java.util.concurrent.TimeUnit

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


object APIClient {

    private var retrofit: Retrofit? = null

    val client: Retrofit
        get() {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            val client = OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .connectTimeout(1, TimeUnit.MINUTES)
                    .retryOnConnectionFailure(true)
                    .build()
            if (retrofit == null) {
                val gson = GsonBuilder()
                        .setLenient()
                        .create()

                retrofit = Retrofit.Builder()
                        .baseUrl("")
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .client(client)
                        .build()


            }
            return this!!.retrofit!!

        }

}



interface APIInterface {

    @POST("login")
    fun callLoginWebservice(@Query("device_token") token: String,
                            @Query("email") userName: String,
                            @Query("password") password: String

    ): Call<UserLoginDetailModel>}
你班上的

  init {
        if (apiInterface == null) {
            apiInterface = APIClient.client.create(APIInterface::class.java)
        }
    }
  apiInterface?.callLoginWebservice(token, userName, password).enqueue(object : Callback<UserLoginDetailModel> {
            override fun onResponse(call: Call<UserLoginDetailModel>, response: Response<UserLoginDetailModel>) {

                loginResponseInterface.onSuccess(loginDetail?.status.toString(),loginDetail ?. errorcode.toString(), loginDetail)
                Log.d("WebServices", "" + loginDetail)

            }

            override fun onFailure(call: Call<UserLoginDetailModel>, t: Throwable) {
                // loginResponseInterface.onSuccess("","", loginDetail);
                loginResponseInterface.onFailure(t)
            }
        })

你的豆子:

class UserLoginDetailModel {
    @SerializedName("_id")
    @Expose
    var id: String? = null


    @SerializedName("email")
    @Expose
    var email: String? = ""

    @SerializedName("name")
    @Expose
    var name: String? = null

    @SerializedName("height_value")
    @Expose
    var heightValue: String? = "0'0''"}

答案 1 :(得分:0)

我自己进行了大量搜索并找到了解决方案。 作为模型类的解决方案并不完美,这是正确的模型类作为我们的要求。

  1. 仅将文件创建为Kotlin。
  2. 将Json转换为Kotlin Class。
  3. 明确项目并运行! :)

    应该可以正常工作!

    data class LoginResultResp(
        val user_info: UserInfo = UserInfo(),
        val status: Status = Status())
    
    data class UserInfo(
        val user_id: String = "", //1010
        val username: String = "", 
        val login_hash: String = "", 
        val facebook_id: String = "",
        val twitter_id: String = "",
        val full_name: String = "", //
        val thumb_url: String = "",
        val photo_url: String = "",
        val mobile: String = "", //
        val email: String = "")
    
    data class Status(
        val status_code: String = "", //-1
        val status_text: String = "" //Success.)