user-44651
user-44651

Reputation: 4124

Determine if an Object is an array or a string

I have some JSON data being returned from the server.

Sometimes the data is an Array other times, it returns an empty string (yes, I know it should return an empty array).
So I need to check FIRST if the type is an instance of a String; if so, I'm going to ignore it and go on with life.
Else I need to read in the values.

How do I determine if an object is a String?

I have looked at this SO question and some other, but I don't think it exactly fits my scenario.
I feel like I'm close, but my code fails denoting I can't cast an object to a string.
But if I cast it to a string... then it will ALWAYS be an instance of a string. Infinite loop.

Here is where I am at so far.

private void myMethod(JSONObject data){
    if (data.has("Notes")){
        Object json = new JSONTokener(data.getJSONObject("Notes")).nextValue();

        if(data.getJSONObject("Notes") instanceof String) {
            JSONArray array = data.getJSONObject("Notes").getJSONArray("Note");
            //do all the array stuff
        }
    }
}

JSON with Array Example

{ "Data": {
        "key": "A value",
        "another key": "some value",
        "Notes": {
            "Note": ["1", "2", "3", "4"]
        } } }

JSON without Array Example

{ "Data": {
        "key": "A value",
        "another key": "some value",
        "Notes": ""
    } }

Upvotes: 0

Views: 93

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191854

You have this

Object json = new JSONTokener(data.getJSONObject("Notes")).nextValue();

But you aren't using json here. You've extracted out getJSONObject("Notes") a second time.

if(data.getJSONObject("Notes") instanceof String) {

Try

if(json instanceof String) {

If that doesn't work, I'd try

JSONObject notesObj = data.optJSONObject("Notes");
if (noteObj == null) {
    // It might be a string, but it was not an object
}

I'm not sure what would happen if you just used getString("Notes") against a value that was an object. It might toString it, but I haven't tried it recently to remember.

Upvotes: 1

Related Questions