如何从 openweather 响应将字符串转换为 kotlin 中的 JSONObject?

How do I convert a string to a JSONObject in kotlin from openweather response?

我现在需要一些帮助将 openweather 响应转换为 JSONObject 我可以使用此 class.

获得响应
import java.net.URL

class ConexionClima {

public fun conseguirRespuestaDeAPI(lat: Double, lon: Double): String ?{

    val apiKey: String = "99ccac116e6924f62f669458a754299c"
    var respuesta: String?
    val urlStr = "https://api.openweathermap.org/data/2.5/onecall?lat=2.0&lon=1.0&appid=99ccac116e6924f62f669458a754299c"

    try{
        respuesta = URL(urlStr).readText(Charsets.UTF_8)
    } catch (e: Exception) {
        respuesta = null
    }
    return respuesta
  }


}

但是当我尝试使用这个函数转换它时

fun resolverPrimerProblema(latitud: Double, longitud: Double): String{
    val cc = ConexionClima()
    val datos : String? = cc.conseguirRespuestaDeAPI(latitud, longitud)
    if (datos != null) {
        val datosJson = JSONObject(datos)
    }

    return("")
}

它只是说“datosJson”设置为空,即使使用的字符串不为空并且是来自 openWeather 的响应。我从调试中知道这一点。

谁能告诉我我哪里做错了或者正确的做法是什么?

提前致谢!

这可能是因为您收到异常,因此您的变量 respuesta 返回为 null

这也可能发生,因为您正在主线程上执行网络调用,因此出现此异常:

NetworkOnMainThreadException

这就是我推荐使用 Volley or Retrofit 等的原因,但如果您热衷于尝试这个,请通过执行以下操作在不同的线程上执行您的代码:

  Thread {
     resolverPrimerProblema(latValue, longValue)
  }.start()