首页 > 解决方案 > Android Kotlin 解析嵌套 JSON

问题描述

我对使用 Kotlin 进行编程仍然很陌生,但我似乎无法找出解析 JSON 的正确方法。我试图从“unackd”数组中的“通知”中获取“标题”和“正文”。

到目前为止,我有:

private fun parse(): Boolean {
    try {
        val ja = JSONArray(jsonData)
        var jo: JSONObject

        users.clear()
        var user: User

        for (i in 0 until ja.length()) {
            jo = ja.getJSONObject(i)

            val name = jo.getString("title")
            val username = jo.getString("body")

            user = User(username,name)
            users.add(user)
        }

        return true
    } catch (e: JSONException) {
        e.printStackTrace()
        return false
    }
}

同时,我的 JSON 结构如下:

{
"unackd": [
    {
        "notification": {
            "title": "Title Test Number 200",
            "body": "passage local they water difficulty tank industry allow increase itself captured strike immediately type phrase driver change save potatoes stems addition behavior grain trap rapidly love refused way television bright 1100"
        },
        "data": {
            "id": "1100",
            "phone": "+15555551234"
        }
    },
    {
        "notification": {
            "title": "Title Test Number 199",
            "body": "announced beside well noted mysterious farm he essential likely deeply vast touch 1099"
        },
        "data": {
            "id": "1099",
            "phone": "+15555551234"
        }
    }
],
"ackd": [
   {
        "notification": {
            "title": "Title Test Number 200",
            "body": "passage local they water difficulty tank industry allow increase itself captured strike immediately type phrase driver change save potatoes stems addition behavior grain trap rapidly love refused way television bright 1100"
        },
        "data": {
            "id": "1100",
            "phone": "+15555551234"
        }
    },
    {
        "notification": {
            "title": "Title Test Number 199",
            "body": "announced beside well noted mysterious farm he essential likely deeply vast touch 1099"
        },
        "data": {
            "id": "1099",
            "phone": "+15555551234"
        }
    }
]
}

我相信我的问题是进入“通知”,然后获取字符串“标题”和“正文”。我试过了

test1 = jo.getJSONObject("notification")

任何帮助,将不胜感激!

编辑:

这是我的 logcat 错误,我认为它与 JSON.typeMismatch 有关:

at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONArray.<init>(JSONArray.java:96)
at org.json.JSONArray.<init>(JSONArray.java:108)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)

标签: jsonparsingkotlin

解决方案


听朋友,用带键的 JSON ARRAY 解析 JSON 对象(如:unackd , ackd)就是这么简单。

有2种方式:

第一种方式)将您的 JSON 解析为 Pojo 架构 http://www.jsonschema2pojo.org/

public class Ackd {

@SerializedName("notification")
@Expose
private Notification_ notification;
@SerializedName("data")
@Expose
private Data_ data;

public Notification_ getNotification() {
return notification;
}

public void setNotification(Notification_ notification) {
this.notification = notification;
}

public Data_ getData() {
return data;
}

public void setData(Data_ data) {
this.data = data;
}

}

    public class Data {

@SerializedName("id")
@Expose
private String id;
@SerializedName("phone")
@Expose
private String phone;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

}

无需对所有类进行解析(如 ackd (Json Array))

第二种方式)

您需要解析名称只有 unackd 而不是 ackd 的 JSON 数组。

String jsonStr = sh.makeServiceCall(url);
JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node
JSONArray unA= jsonObj.getJSONArray("unackd");

for (int i = 0; i < unA.length(); i++) 
{
  JSONObject c = unA.getJSONObject(i);
  String title= c.getString("title");
  String body= c.getString("body");
}

推荐阅读