正如您可能知道的那样,我对此非常陌生,但我正在尝试使用Android中的Kotlin解析带有Volley的JSON url。url包含嵌套对象,而不是嵌套数组。
我可以显示“问卷”中的所有内容,但我只想显示"typeOfQuestion“。我该怎么做?
MainActivity.kt:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
questionTV = findViewById(R.id.idTVQuestion)
answerTV = findViewById(R.id.idTVAnswer)
typeTV = findViewById(R.id.idTVType)
val queue: RequestQueue = Volley.newRequestQueue(applicationContext)
val request = JsonObjectRequest(Request.Method.GET, url, null, { response ->
loadingPB.setVisibility(View.GONE)
try {
val question: String = response.getString("question")
val answer: String = response.getString("answer")
val typeOfQuestion: String = response.getString("typeOfQuestion")
questionTV.text = question
answerTV.text = answer
typeTV.text = typeOfQuestion
} catch (e: Exception) {
e.printStackTrace()
}
}, { error ->
Log.e("TAG", "RESPONSE IS $error")
Toast.makeText(this@MainActivity, "Fail to get response", Toast.LENGTH_SHORT)
.show()
})
queue.add(request)
}
}这是JSON:
{
"questionnaire": {
"question": "Where do you live?",
"answer": "In the mountains",
"typeOfQuestion": "Informative
}
}发布于 2022-08-14 04:30:08
在另一个json object.If中有对象,您需要从子对象访问字段,您需要获得子jsonObject,然后从对象获取字段。
var questionnaire = response.getJSONObject("questionnaire")您需要从问卷调查object.Like中获取字段。
val question: String = questionnaire.getString("question")
val answer: String = questionnaire.getString("answer")
val typeOfQuestion: String = questionnaire.getString("typeOfQuestion")https://stackoverflow.com/questions/73348497
复制相似问题