Home > front end >  Get a specific value of JSON data Kotlin
Get a specific value of JSON data Kotlin

Time:04-27

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

CodePudding user response:

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)

CodePudding user response:

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