我有两个例子:
-
Json文件-example.Json:
{ "users": [ { "id": "1", "name": "ABC", "email": "abc@gmail.com", "contact": { "mobile1": "0123456789", "mobile2": "0123456789", "mobile3": "0123456789" } }, { "id": "2", "name": "XYZ", "email": "xyz@gmail.com", "contact": { "mobile1": "0123456789", "mobile2": "0123456789", "mobile3": "0123456789" } } ] }
-
Json文件-[data.Json](https://github.com/rolling-scopes-school/rs.android.task.6/blob/master/data/data.json)
为了解析这个json文件,我使用函数:
fun getJsonDataFromAsset(context: Context, fileName: String): String? {
val jsonString: String
try {
jsonString = context.assets.open(fileName).bufferedReader().use { it.readText() }
System.out.println("jsonString" + jsonString)
} catch (ioException: IOException) {
ioException.printStackTrace()
return null
}
return jsonString
}
在第一个原因我有:
try {
val obj = JSONObject(getJsonDataFromAsset(this,"example.json"))
val itemsArray = obj.getJSONArray("users")
.....}
没事!
在第二我有:
try {
val obj = JSONObject(getJsonDataFromAsset(this,"data.json"))
val itemsArray = obj.getJSONArray("item")
.....}
我遇到了麻烦——没有物有所值。
如果我使用字段";通道":
try {
val obj = JSONObject(getJsonDataFromAsset(this,"example.json"))
val itemsArray = obj.getJSONArray("channel")
.....}
我收到一条错误消息:
"W/System.err:org.json.JSONException:值创意火花">
怎么了?
我解决了这个问题:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val url = "https://raw.githubusercontent.com/rolling-scopes-school/rs.android.task.6/master/data/data.json"
val request = ServiceBuilder.buildService(ApiInterface::class.java)
val call = request.getItems(url)
call.enqueue(object : Callback<GitResponse> {
override fun onFailure(call: Call<GitResponse>, t: Throwable) {
Toast.makeText(this@MainActivity, "${t.message}", Toast.LENGTH_LONG).show()
}
override fun onResponse(call: Call<GitResponse>, response: Response<GitResponse>) {
if (response.isSuccessful) {
recyclerview.apply {
progress_bar.visibility = View.GONE
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = MyAdapter(response.body()?.channel?.item ?: listOf())
recyclerview.adapter = adapter
(adapter as MyAdapter).notifyDataSetChanged()
}
}
}
})
}
}