JSON Objects Between PHP and Objective-C

My iPhone application is grabbing a JSON object from a PHP website.

An object on a PHP site has several properties that are integer.

Properties that are retrieved from the database are returned from the database (where they are stored as INT) look like this in JSON:"seatedplayers":"3"

Properties that have been changed in PHP code look like this in JSON: "currentseat":1

In my Obj-c, I use NSNumberFormatter to format them correctly as follows:
[numFormatter numberFromString:[jsonObject objectForKey:@"seatedplayers"]];(jsonObject is NSDictionary)

This code works fine on properties with quotes around the value, but not on others. If I add stringValueObjective-C to my code, it will work with properties without quotes, but not with quotes.

Now, my big problem here is that this application will need to communicate with sites that I personally won’t write, so what code in Objective-C could I write to handle any instance?

EDIT
This is how I get the NSDictionary jsonObject.

- (NSDictionary *) getJSONObjectFromWebAddress:(NSString *) address {
// Prepare the URL Request
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:address]];

// Perform the request, expecting JSON back
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSError *error;
SBJsonParser *parser = [[SBJsonParser new] autorelease];
NSDictionary *jsonObject = [parser objectWithString:responseString error:&error];
if (!jsonObject) {
    NSLog(@"%@", error);
}

[responseString release];
return jsonObject;
}
+3
source share
1 answer

I had the same problem. Fortunately, both NSString and NSNumber respond to intValue, so you can safely use this.


//NSDictionary* myJsonParsed;
[NSString stringWithFormat:@"%d", [[myJsonParsed valueForKey:@"stringOrInt"] intValue]];
+2
source

Source: https://habr.com/ru/post/1788622/


All Articles