我想从API获取一个简单的字符串。
通常,我可以从具有以下功能的API获得所需的一切:
class OrderRepositoryImpl(val orderService: OrderService) : OrderRepository {
override fun getPaymentMethods(id: String, success: (List<PaymentMode>) -> Unit, failure: (Throwable) -> Unit): Subscription {
return orderService.getPaymentMethods(id)
.subscribeOn(Schedulers.io())
.map { it.entrySet() }
.map { it.map { it.value }.map {it.asJsonObject } }
.map { it.map { PaymentMode().apply { loadFromJson(it) } } }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ success.invoke(it) }, { failure.invoke(it) })
}
}
在OrderService中:
@GET("api/order/payment/modes/list/{id}")
fun getPaymentMethods(@Path("id") id: String): Observable<JsonObject>
这在具有常规Json对象的API上非常有效。
但是今天,我遇到了一个问题:我有一个具有唯一字符串的API,如下所示:
"validated"
或:
"draft"
所以我做了跟随函数(在OrderRepositoryImpl类中):
override fun getOrderStatus(id: String, success: (String) -> Unit, failure: (Throwable) -> Unit) =
orderService.getOrderStatus(id)
.subscribeOn(Schedulers.io())
.map { it }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ success.invoke(it.toString()) }, { failure.invoke(it) } )
在订单服务中:
@GET("api/order/checkout/{id}/status")
fun getOrderStatus(@Path("id") id: String): Observable<JsonObject>
我这样称呼这个方法:
fun getOrderStatus(id : Long) {
orderRepository.getOrderStatus(id.toString(), {
println("SUCCESS !")
println("STATUS == $it")
}, {
println("FAILURE...")
})
}
但是我从“ success.invoke”行中什么也没得到。当我在代码中调用此方法时,我的日志中总是带有“ FAILURE” ...即使其中一个日志行是:
D/OkHttp: "validated"
如果成功的话,这正是我想要看到的。
我知道我可以获取并解析json对象而不是字符串,这很奇怪,但是我从中学到了一些东西...
如何从API获取简单的字符串?
答案 0 :(得分:0)
好的,我很SO愧。
因此,我在“ FAILURE ...”部分中打印了错误,并且得到了类似的信息:
got jsonPrimitive but expected jsonObject
由于API只是向我返回一个字符串,而不是一个对象,因此将其称为Json Primitive。 所以我只是更改了OrderService中函数的返回值:
@GET("api/order/checkout/{id}/status")
fun getOrderStatus(@Path("id") id: String): Observable<JsonPrimitive>
感谢您的有用评论。
答案 1 :(得分:0)
interface ServiceInterFace {
@POST("api/order/checkout/{id}/status")
fun getOrderStatus(@Path("id") id: String): Call<String>
}
// calling from your main class
val id: String? = null
val retrofit = Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.baseUrl("----Your link here-----")
.build()
val scalarService = retrofit.create(ServiceInterFace::class.java!!)
val stringCall = scalarService.getOrderStatus(id)
stringCall.enqueue(object : Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
if (response.isSuccessful) {
val responseString = response.body()//get response here
}
}
override fun onFailure(call: Call<String>, t: Throwable) {
Toast.makeText(this@Main2Activity, "Failed to connect server",
Toast.LENGTH_SHORT).show()
}
})
//import
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'