0

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": ""
    } }
3
  • 1
    getJSONObject returns a JSONObject, which is not instanceof String Commented Dec 9, 2016 at 19:27
  • I need to know the what the contents of "Notes" is. Is it a string or is it an array? Commented Dec 9, 2016 at 19:30
  • I think you want get("Notes") instanceof since get is what returns the Object class. You could also try one of the opt methods that returns null when it cannot convert. Commented Dec 9, 2016 at 19:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.