【发布时间】:2018-03-20 22:01:46
【问题描述】:
我是 Kotlin 的新手,我找到了 Klaxon 库来解析 JSON。我找不到如何执行 url(http://localhost:8080/items/2)、读取 JSON 字符串并将数据保存到变量并将它们打印到控制台。 CreatedAt 和 UpdatedAt 我不需要保存。
来自 url 的 JSON:
{
"brand": "Ferrero",
"name": "Nutella",
"healthy": false,
"date": "2017-03-14T00:00:00.000Z",
"id": 2,
"createdAt": "2018-03-14T13:33:22.000Z",
"updatedAt": "2018-03-20T21:23:44.000Z"
}
代码:
class DetailItem : AppCompatActivity() {
var itemId : String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail_item)
itemId = intent.getStringExtra("itemId")
}
override fun onResume() {
super.onResume()
example()
}
private fun parse(name: String) : Any{
val cls = Parser::class.java
val inputStream = cls.getResourceAsStream(name)!!
return Parser().parse(inputStream)!!
}
private fun example(){
val url = "http://192.168.99.100:8080/items/" + itemId
val obj = parse("url") as JsonObject
val brand = obj.string("brand")
val name = obj.string("name")
println(brand + name)
}
【问题讨论】:
-
到目前为止你写过代码吗? Here's the documentation for Klaxon
-
对不起,我的回答迟了。我添加了代码。错误是:kotlin.KotlinNullPointerException
-
哪一行抛出异常?
-
at DetailItem.parse(val inputStream = cls.getResourceAsStream(name)!!) at DetailItem.example(val obj = parse("url") as JsonObject) at DetailItem.onResume(example() )
-
不应该
parse("url")是parse(url)吗?不确定这是否足够,但这似乎是一个有问题的错字