0

I'm still pretty new to programming with Kotlin but I can't seem to figure out the correct way to parse my JSON. I'm attempting to get "title" and "body" from "notification" in "unackd" array only.

So far I've got:

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
    }
}

Meanwhile my JSON is structured as so:

{
"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"
        }
    }
]
}

I believe my issue is getting into "notification" to then get the strings "title" and "body". Which I've tried

test1 = jo.getJSONObject("notification")

Any help would be appreciated!

EDIT:

This is my logcat error, I assume it has to do with the 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)
J. Doe43
  • 207
  • 2
  • 6
  • 20

4 Answers4

1

Listen friend , parsing the JSON Object with JSON ARRAY with key (like: unackd , ackd) is so simple.

There are 2 ways:

1st Way) Parse your JSON to Pojo schema 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;
}

}

No need to Make all class for parsing (like ackd (Json Array))

2nd Way)

You need to PARSE JSON array with name only unackd not ackd.

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");
}
straya
  • 5,002
  • 1
  • 28
  • 35
Zafar Hussain
  • 264
  • 2
  • 10
1

The exception message suggests that you're passing data that doesn't represent a JSON array when instantiating JSONArray:

at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONArray.<init>(JSONArray.java:96)

The JSON you've attached is in fact a JSON object, notice that its content is enclosed in {}. Hence to access the "unackd" array, you need to first create a JSON object, and then reference the array inside of it:

val root = JSONObject(jsonData)
val ja = root.getJSONArray("unackd")
// the rest of your code goes here
Egor
  • 39,695
  • 10
  • 113
  • 130
0
  1. Auto generate Data class
    http://www.jsonschema2pojo.org/

  2. I suppose that your class is named Response.java

    Response object=new Gson().fromjson(jsonContentFile,Response.class);

Bulma
  • 990
  • 3
  • 16
  • 35
0

Following data classes are generated for your JSON using https://json2kotlin.com

data class Json4Kotlin_Base (

    val unackd : List<Unackd>,
    val ackd : List<Ackd>
)

and

data class Data (

    val id : Int,
    val phone : Int
)

and

data class Notification (

    val title : String,
    val body : String
)

and

data class Ackd (

    val notification : Notification,
    val data : Data
)

and

data class Unackd (

    val notification : Notification,
    val data : Data
)

Here's a video that explains how to implement these when generated.

Syed Absar
  • 2,274
  • 1
  • 26
  • 45