I am creating an app for as existing website. They currently has the JSON in the following format :
[
{
"id": "value",
"array": "[{\"id\" : \"value\"} , {\"id\" : \"value\"}]"
},
{
"id": "value",
"array": "[{\"id\" : \"value\"},{\"id\" : \"value\"}]"
}
]
which they parse after escaping the \ character using Javascript.
My problem is when i parse it in iOS using the following command :
NSArray *result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&localError];
and do this :
NSArray *Array = [result valueForKey:@"array"];
Instead of an Array
I got NSMutableString
object.
The website is already in production so I just cant ask them to change their existing structure to return a proper
JSON
object. It would be a lot of work for them.So, until they change the underlying stucture, is there any way i can make it work in
iOS
like they do withjavascript
on theirwebsite
?
Any help/suggestion would be very helpful to me.
As people just said above, you must use the
NSJSONSerialization
to deserialiseJSON
into usable data structures asNSDictionary
orNSArray
first.However, if you want to map the content of your
JSON
to your Objective-C objects, you will have to map each attribute from theNSDictionary/NSArray
to your object property. This might be a bit painful if your objects have many attributes.In order to automatise the process, I recommend you to use the Motis category on
NSObject
(a personal project) to accomplish it, thus it is very lightweight and flexible. You can read how to use it in this post. But just to show you, you just need to define a dictionary with the mapping of yourJSON
object attributes to your Objective-C object properties names in yourNSObject
subclasses:and then perform the parsing by doing:
The setting of the properties from the dictionary is done via
KeyValueCoding
(KVC) and you can validate each attribute before setting it viaKVC
validation.Hoping it helps you as much it helped me.
Try this simple method....
@property NSMutableURLRequest * urlReq;
@property NSURLSession * session;
@property NSURLSessionDataTask * dataTask;
@property NSURLSessionConfiguration * sessionConfig;
@property NSMutableDictionary * appData;
@property NSMutableArray * valueArray; @property NSMutableArray * keysArray;
-(void)getData
{ self.urlReq = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:self.linkString]];
JSON default method :
Return method: