Kotlin解析单个JSON对象报错问题及解决
解决单个JSON对象字段解析的Kotlin问题
问题背景
你从API拿到了一段仅包含单个对象的JSON数据,尝试用Kotlin解析时触发了JSONException,错误提示JSONObject["deliverable"] is not a JSONObject。
原始JSON数据
{ "address": "mickaelnanah@gmail.com", "username": "mickaelnanah", "domain": "gmail.com", "md5Hash": "0f6082627bfdeb56a3792f52ce8f0cb8", "validFormat": true, "deliverable": true, "fullInbox": false, "hostExists": true, "catchAll": false, "disposable": false, "free": true }
初始出错代码
val jsonObj = JSONObject(jSonString.substring(jSonString.indexOf("{"), jSonString.lastIndexOf("}") + 1)) val mail = Email(jsonObj.getJSONObject("deliverable") as String) println(mail.email)
报错信息
Exception in thread "main" org.json.JSONException: JSONObject["deliverable"] is not a JSONObject.
错误原因
问题出在方法调用不匹配:deliverable是一个布尔类型的字段(值为true),但你使用了getJSONObject()方法去获取它——这个方法是用来提取嵌套的JSON对象的,自然会抛出类型不匹配的异常。
正确解决方案
要直接获取单个字段的值,应该使用通用的get()方法(或者对应类型的专用方法,比如getBoolean()),再按需转换类型。你已经找到了正确的代码:
val jsonObj = JSONObject(jSonString.substring(jSonString.indexOf("{"), jSonString.lastIndexOf("}") + 1)) val mail: String = jsonObj.get("deliverable").toString()
如果想更严谨地处理布尔类型,也可以直接调用getBoolean()方法,再转成字符串:
val deliverableStatus = jsonObj.getBoolean("deliverable") val mail: String = deliverableStatus.toString()
这样就能正确解析deliverable字段的值,避免类型错误。
内容的提问来源于stack exchange,提问作者user9172697
相关产品推荐
相关产品推荐

