获取JSON Data Kotlin的特定值

发布于 2025-01-24 04:08:43 字数 2026 浏览 0 评论 0原文

我正在尝试从我的JSON数据中获得特定值。我可以成功调用整个JSON数据,jsonOutput。但是事实是,当我在jsonOutput中调用特定值时,它显示了我nullpointererror。我不知道为什么在调用数据类时会丢失数据。我标记了我因而丢失的部分,问题出现在这里。如何获得adminarea1

我共享一个数据类作为示例。您可以使用“ JSON的Kotlin Data Class File”创建数据类。 我提到了许多答案和示例,但很难知道原因。

我的代码

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
        }
    }
}
}

数据类

I am trying to get a specific value from my JSON data. I could successfully call the entire json data,jsonOutput. But the thing is when I call a specific value in the jsonOutput, it shows me nullPointerError. I do not know why I lost the data when I call my data class. I marked the part I lost them with The problem occurs here. How can I get adminArea1?

I shared one data class as a sample. You can create the data classes with "Kotlin data class File from JSON".
I referred to many answers and examples but was hard to know the reason.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

活泼老夫 2025-01-31 04:08:43

使用此类并使用响应数据类解析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(jsonOutput,reponse :: class.java)

Use this class and use Response data class to parse 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(jsonOutput, Reponse::class.java)

说好的呢 2025-01-31 04:08:43

这是由于API通信引起的。我通过放置OkhttpClient解决了问题。我添加了代码,以帮助任何有同样问题的人。

   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) }}

It was caused due to API communication. I solved my problem by putting okHttpClient. I added the code to help anybody having the same question.

   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) }}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文