I’m working with django-piston and parsing that JSON output in Objective-C, but having some trouble because the output doesn’t contain any top-level labels. Every example I’ve come across has the data parsed into a dictionary, then generating an array based on objectForKey:@”foo” but in my case, I have no top-level text to parse based on.
Here’s the JSON generated by Piston:
[
{
"text": "Pain Intensity",
"question_number": 1,
"id": 1
},
{
"text": "Personal Care (washing, dressing, etc.)",
"question_number": 2,
"id": 2
},
{
"text": "Lifting",
"question_number": 3,
"id": 3
},
{
"text": "Walking",
"question_number": 4,
"id": 4
},
{
"text": "Sitting",
"question_number": 5,
"id": 5
}
]
What I’d like to do is end up with an array of objects containing an id, text and question number property.
Any advice?
IF you are using iOS 5 (for an iOS app) or OS 10.7 (for a Mac app), then the NSJSONSerialization class is built right in:
This will work whenever the myData object (an NSData instance) contains a valid JSON string using one of the supported JSON encodings, and the top-level element of that JSON string is an array as it is in your example.
When you do this with your example JSON string, you should get an NSArray containing 5 dictionaries. So you could do something like this:
The above assumes you’ve defined a class called MyClass with properties called text, questionNumber, and id.