Importar las librerías necesarias
1 2 |
com.squareup.okhttp3:okhttp:4.9.3 com.google.code.gson:gson:2.8.8 |

Código para leer el fichero JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import com.google.gson.Gson import okhttp3.OkHttpClient import okhttp3.Request import java.io.IOException data class Persona(val nombre: String, val edad: Int) fun main() { val url = "https://jesusninoc.com/persona.json" val client = OkHttpClient() val request = Request.Builder() .url(url) .build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Unexpected code $response") val gson = Gson() val persona: Persona = gson.fromJson(response.body!!.string(), Persona::class.java) println("Nombre: ${persona.nombre}, Edad: ${persona.edad}") } } |
