我正在尝试阅读有关我在大学的课程安排的json文件,可从此链接获取它:http://diag.uniroma1.it/pannello/?q=export_json
[我尝试使用https://developer.android.com/training/volley/simple来完成此操作,该工具适用于https://helloacm.com/api/factor/?cached&n=10中非常简单的json文件(在给定数字的情况下,它返回自身的分解)。
但是应用相同的推理是行不通的。实际上,以前运行良好的应用程序现在崩溃了。
fun factors (x: String){
val queue = Volley.newRequestQueue(this)
//val url = "https://helloacm.com/api/factor/?cached&n="+x
val url = "http://diag.uniroma1.it/pannello/?q=export_json"
var reply : String = ""
// Request a string response from the provided URL.
val stringRequest = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
reply = JSONObject(response.toString()).toString()
output.text=reply
},
Response.ErrorListener { error: VolleyError? -> output.text = error.toString() })
// Add the request to the RequestQueue.
queue.add(stringRequest)
}
是什么问题?文件太大尊重上一个吗?我真的是新手
之所以不起作用,是因为您正在接收JSON数组,但您试图将其解析为JSON对象。为了简化反序列化,您可以检查Google's Gson Library。这是Gson实现的示例:
将以下依赖项添加到build.gradle
文件,并使用Gradle同步项目:
implementation 'com.google.code.gson:gson:2.8.6'
创建代表您的JSON对象的模型:
import com.google.gson.annotations.SerializedName
data class DataObject(
@SerializedName("data")
val data: String,
@SerializedName("Descrizione")
val descrizione: String,
@SerializedName("Id")
val id: String,
@SerializedName("id_aula")
val idAula: String,
@SerializedName("minuti_fine")
val minutiFine: String,
@SerializedName("minuti_inizio")
val minutiInizio: String,
@SerializedName("nome_aula")
val nomeAula: String,
@SerializedName("ora_fine")
val oraFine: String,
@SerializedName("ora_inizio")
val oraInizio: String
)
现在您可以修改函数以反序列化JSON:
fun factors(x: String) {
val queue = Volley.newRequestQueue(this)
//val url = "https://helloacm.com/api/factor/?cached&n="+x
val url = "http://diag.uniroma1.it/pannello/?q=export_json"
var reply: List<DataObject> = listOf()
// Request a string response from the provided URL.
val stringRequest = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
reply = Gson().fromJson(response, object : TypeToken<List<DataObject>>() {}.type)
output.text = reply
},
Response.ErrorListener { error: VolleyError? -> output.text = error.toString() })
// Add the request to the RequestQueue.
queue.add(stringRequest)
}