程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ JSON Array Kotlin 处为 BEGIN_OBJECT大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ JSON Array Kotlin 处为 BEGIN_OBjeCT?

开发过程中遇到预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ JSON Array Kotlin 处为 BEGIN_OBjeCT的问题如何解决?下面主要结合日常开发的经验,给出你关于预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ JSON Array Kotlin 处为 BEGIN_OBjeCT的解决方法建议,希望对你解决预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ JSON Array Kotlin 处为 BEGIN_OBjeCT有所启发或帮助;

我想检索一个 JsON 数组,我该如何调整我的代码库。我使用了改造库来检索数据,并使用了 MVVM 架构。我收到错误预期为 BEGIN_ARRAY 但在第 1 行第 2 列路径 $ 处为 BEGIN_OBjeCT。

这是我的端点类:

 @GET("v2/venues/search")
    fun fetchAllVenues(): Call<List<Venue>>
    }

这是我的存储库类:

class VenueRepository {

    private var APIInterface: VenuesEndpoint? = null

    init {
        APIInterface = apiclient.getapiclient().create(VenuesEndpoint::class.java)
    }

    fun fetchAllVenues(): mutablelivedata<List<Venue>?> {

        val data = mutablelivedata<List<Venue>?>()

        APIInterface?.fetchAllVenues()?.enqueue(object : CallBACk<List<Venue>> {

            overrIDe fun onFailure(call: Call<List<Venue>>,t: ThrowablE) {
                data.value = null
            }

            overrIDe fun onResponse(
                call: Call<List<Venue>>,response: Response<List<Venue>>
            ) {

                val res = response.body()
                if (response.code() == 200 && res != null) {
                    data.value = res
                } else {
                    data.value = null
                }

            }
        })

        return data

    }


}

这是我的模型类:

data class Venue(var ID:Int,var name:string)

这是我的视图模型类:

class Venueviewmodel : viewmodel() {
    private var venueRepository: VenueRepository? = null
    var postModelListliveData: mutablelivedata<List<Venue>?>? = null


    init {
        venueRepository = VenueRepository()
        postModelListliveData = mutablelivedata()
    }

    fun fetchAllVenues() {
        postModelListliveData = venueRepository?.fetchAllVenues()

    }


}

这是我要检索的 JsON:

"response": { "venues": [ { "ID": "4b83cb72f964a520d71031e3" "name": "Stadhuis" "contact": { "phone": "+3114010" "formattedPhone": "+31 14010" "twitter": "rotterdam" } "LOCATIOn": { "address": "Coolsingel 40" "lat": 51.92258962728412 "lng": 4.480227190204032 "labeledLatLngs": [ "0": { "label": "display" "lat": 51.92258962728412 "lng": 4.480227190204032 } ] "postalCode": "3011 AD" "cc": "NL" "city": "Rotterdam" "state": "ZuID-Holland" "country": "Nederland" "formattedAddress": [ "0": "Coolsingel 40" "1": "3011 AD Rotterdam" "2": "Nederland" 

解决方法

问题是,响应返回您 venues 而您期待的是 List<Venue>,所以对您有用的是,创建另一个如下所示的数据类:

data class Venues(
 val venues: List<Venue>
)

然后在 GET 请求中返回 Call<Venues> 请告诉我是否可以为您解决此问题:)

更新

好的,这有点冗长,但最后是您的详细解决方案,希望这可以为您解决所有问题!

视图模型

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel

class ViewModel : ViewModel() {

    private val repository = Repository()

    fun getData(longLat: String,date: String): LiveData<mainResponse?> {

        repository.fetch(longLat,datE)
        return repository.data
    }
}

存储库

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import retrofit2.Call
import retrofit2.CallBACk
import retrofit2.Response

class Repository {

    private val _data: MutableLiveData<mainResponse?> = MutableLiveData(null)
    val data: LiveData<mainResponse?> get() = _data

    fun fetch(longlat: String,date: String) {

        val retrofit = Retro()
        val api = retrofit.retro.create(api::class.java)

        api.get(
            longLat = longlat,date = date
        ).enqueue(object : CallBACk<mainResponse>{

            override fun onResponse(call: Call<mainResponse>,response: Response<mainResponse>) {

                val res = response.body()
                if (response.code() == 200 && res != null) {

                    _data.value = res

                } else {

                    _data.value = null
                }
            }

            override fun onFailure(call: Call<mainResponse>,t: ThrowablE) {
                _data.value = null
            }
        })
    }
}

主活动

private val viewModel by viewModels<ViewModel>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceStatE)
    setContentView(R.layout.activity_main)

    viewModel.getData(
        longLat = "40.7,-74",// sample latitude and longitude
        date = "20210715" // date format is: YYYymMDD
    ).observe(this,Observer {

        it?.let { res ->

            res.response.venues.forEach { venue ->

                val name = venue.name
                val LOCATIOn = venue.LOCATIOn

                Log.d("name ",Name)
                Log.d("address ",LOCATIOn.address)
            }
        }
    })
  }
}

API接口

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface api {

    @GET("v2/venues/search")
    fun get(
        @Query("ll") longLat: String,@Query("client_id") id: String = Const.clientId,@Query("client_secret") secret: String = Const.clientSecret,@Query("v") date: String
    ): Call<mainResponse>
}

模型类

主响应

数据类 mainResponse( val 响应:响应 )

回复

data class Response(
val venues: List<Venue>,val confident: Boolean
)

位置

data class LOCATIOn(
val address: String,val crossStreet: String,val lng: Double,val lat: Double
)

场地

data class Venue(
val id: String,val name: String,val LOCATIOn: LOCATIOn
)

常量

object Const {

const val BASE_URL = "https://api.foursquare.com"
const val clientId = "" // add yours
const val clientSecret = "" // add yours
}

复古

class Retro {

val retro = Retrofit.builder()
    .baseUrl(Const.bASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build()
}

依赖项:确保添加activity-ktx以便在活动中使用ViewModel

def coroutInes_version = "1.4.2"
implementation "org.jetbrains.kotlinx:kotlinx-coroutInes-core:$coroutInes_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutInes-android:$coroutInes_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutInes-play-services:$coroutInes_version"

def lifecycle_version = "2.3.1"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"

def retrofit_version = "2.9.0"
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"

implementation "androidx.activity:activity-ktx:1.2.3"

大佬总结

以上是大佬教程为你收集整理的预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ JSON Array Kotlin 处为 BEGIN_OBJECT全部内容,希望文章能够帮你解决预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ JSON Array Kotlin 处为 BEGIN_OBJECT所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。