获取 JSON 数据的特定值 Kotlin

Get a specific value of JSON data Kotlin

我正在尝试从我的 JSON 数据中获取特定值。我可以成功调用整个 json 数据,jsonOutput。但问题是当我在 json 输出中调用特定值时,它会显示 nullPointerError。不知道为什么调用我的数据class就丢了数据。我用 The problem occurs here 标记了丢失的部分。我怎样才能得到adminArea1

我分享了一个数据class作为样本。您可以使用“来自 JSON 的 Kotlin 数据 class 文件”创建数据 classes。 我参考了很多答案和例子,但很难知道原因。

My code

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

    binding.networkBtn.setOnClickListener(View.OnClickListener {

        var thread = NetworkThread()
        thread.start()
    })
}
inner class NetworkThread : Thread() {
    override fun run() {
        var url =
            URL("https://www.mapquestapi.com/geocoding/v1/reverse?key=LBK8QWxDPYHfmeYVlEP1IO3BVbWHyznB&" +
                    "location=Your_laptitue,Your_longitute&includeRoadMetadata=true&includeNearestIntersection=true")

        var countryCodeBufferedReader =
            BufferedReader(InputStreamReader(url.openConnection().getInputStream()))

        var stringBuffer = StringBuffer()

        do {
            var string = countryCodeBufferedReader.readLine()
            if (string != null) {
                stringBuffer.append(string)
            }
        } while (string != null)

        var jsonObject = JSONObject(stringBuffer.toString())

        val gson: Gson = GsonBuilder().setPrettyPrinting().create()
        val jsonOutput: String = gson.toJson(jsonObject)

        //The problem occurs here
        var countryData = gson.fromJson(jsonOutput, NameValuePairsXXXXX::class.java)

        val jsonOutput2 = countryData.adminArea1

        Log.d("jsonOutput", jsonOutput)
        Log.d("jsonOutput2", jsonOutput2)

        runOnUiThread {
            binding.lapLonText.text = jsonOutput2
        }
    }
}
}

Data class

使用此 class 并使用响应数据 class 解析 json,

data class Response(
    val options: Options? = null,
    val results: List<ResultsItem?>? = null,
    val info: Info? = null
)

data class Options(
    val thumbMaps: Boolean? = null,
    val maxResults: Int? = null,
    val ignoreLatLngInput: Boolean? = null
)

data class LatLng(
    val lng: Double? = null,
    val lat: Double? = null
)

data class Info(
    val statuscode: Int? = null,
    val copyright: Copyright? = null,
    val messages: List<Any?>? = null
)

data class ProvidedLocation(
    val latLng: LatLng? = null
)

data class Copyright(
    val imageAltText: String? = null,
    val imageUrl: String? = null,
    val text: String? = null
)

data class DisplayLatLng(
    val lng: Double? = null,
    val lat: Double? = null
)

data class LocationsItem(
    val dragPoint: Boolean? = null,
    val displayLatLng: DisplayLatLng? = null,
    val adminArea4: String? = null,
    val unknownInput: String? = null,
    val adminArea5: String? = null,
    val adminArea6: String? = null,
    val postalCode: String? = null,
    val adminArea1: String? = null,
    val adminArea3: String? = null,
    val sideOfStreet: String? = null,
    val type: String? = null,
    val adminArea6Type: String? = null,
    val geocodeQualityCode: String? = null,
    val adminArea4Type: String? = null,
    val linkId: String? = null,
    val roadMetadata: Any? = null,
    val street: String? = null,
    val nearestIntersection: Any? = null,
    val adminArea5Type: String? = null,
    val mapUrl: String? = null,
    val geocodeQuality: String? = null,
    val adminArea1Type: String? = null,
    val adminArea3Type: String? = null,
    val latLng: LatLng? = null
)

data class ResultsItem(
    val locations: List<LocationsItem?>? = null,
    val providedLocation: ProvidedLocation? = null
)

var countryData = gson.fromJson(json输出, Reponse::class.java)

由于API沟通造成的。我通过将 okHttpClient.xml 解决了我的问题。我添加了代码来帮助任何有同样问题的人。

   val client  = OkHttpClient()
        val request = Request.Builder().url(url).build()
        client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                Log.d("fail", "fail")
            }

            override fun onResponse(call: Call, response: okhttp3.Response) {
                var body = response.body?.string()

                Log.d("body", "$body")

                val jsonObject2 : JSONObject = JSONObject(body.toString())
                val jsonOutput2 = gson.fromJson(body, Response::class.java)
                val test2 = jsonOutput2.results?.get(0)?.locations?.get(0)?.adminArea1.toString()
                Log.d("test2", test2) }}