I have some problem with JSON parsing. When I hit URL, I've got JSON response like this:
//JSON 1
{ "data":
{"array":
["3",
{"array":
[
{"id":"1","message":"Hello","sender":"inot"},
{"id":"2","message":"World","sender":"inot"},
{"id":"3","message":"Hi","sender":"marza"}
]
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
But if the result of data is just 1, the JSON response is like this:
//JSON 2
{ "data":
{"array":
["3",
{"array":
{"id":"3","message":"Hi","sender":"marza"}
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
I implement this code to get the id, message and sender value, and work fine on JSON 1, but error on JSON 2. I use JSON-Framework. And the question is how to detect that the JSON response is object ({ }) or array ([ ]) ??
// Parse the string into JSON
NSDictionary *json = [myString JSONValue];
// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(@"id = %@",[item objectForKey:@"id"]);
NSLog(@"message = %@",[item objectForKey:@"message"]);
NSLog(@"sender = %@",[item objectForKey:@"sender"]);
}
How do you check if it is a JSONArray or JSON object in Java? JSONArray interventions; if(intervention == null) interventions=jsonObject. optJSONArray(“intervention”); This will return you an array if it's a valid JSONArray or else it will give null .
Yes, json arrays can contain any valid json string: objects with different key/value pairs, other arrays, numbers, strings, booleans all in the same array.
JSON SyntaxJSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.
You can use id
and check if the object that you get is NSArray or NSDictionary like this:
id item = [json valueForKeyPath:@"data.array"];
if ([item isKindOfClass:[NSArray class]]) {
// item is an array
}
else if ([item isKindOfClass:[NSDictionary class]]) {
// item is a dictionary
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With