Stornu2
Stornu2

Reputation: 2332

Converting NSString to JSON with NSJSONSerialization is not working

I have this function:

- (void)checkLogin:(NSString *)pLogin andPassword:(NSString*) pPassword {
    //Create the data object.
    NSMutableDictionary *tLoginAndPasword = [NSMutableDictionary dictionaryWithObjectsAndKeys:pLogin,@"Login",pPassword,@"Password", nil];
    NSMutableDictionary *tData = [NSMutableDictionary dictionaryWithObjectsAndKeys:[_Util serializeDictionary:tLoginAndPasword],@"Data", nil];
    //Call the login method.
    NSData *tResponse = [_Util getLogin:tData];
    if (tResponse != Nil) {
        _oLabelErrorLogin.hidden = YES;
        [_Util setUser:pLogin andPassword:pPassword];
        NSMutableDictionary *tJSONResponse =[NSJSONSerialization JSONObjectWithData:tResponse options:kNilOptions error:nil];
        NSString *tPayload = [tJSONResponse objectForKey:@"Payload"];
        if([[tJSONResponse objectForKey:@"StatusCode"]  isEqual: @"424"]) {
            //Set global values.
            NSData *tPayloadData = [tPayload dataUsingEncoding:NSUTF8StringEncoding];
            if ([NSJSONSerialization isValidJSONObject:tPayloadData]) {
                _Payload = [NSJSONSerialization JSONObjectWithData:tPayloadData options:kNilOptions error:nil];
                _RowCount = _Payload.count;
            } else {
                NSLog(@"JSON Wrong String %@",tPayload);
            }
        } else if([[tJSONResponse objectForKey:@"StatusCode"]  isEqual: @"200"]){
            _Payload = Nil;
        }
    } else {
        //Set global values.
        _Payload = Nil;
        _oLabelErrorLogin.hidden = NO;
        //Clear login data.
        _oLogin.text = @"";
        _oPassword.text = @"";
        [_Util setUser:@"" andPassword:@""];
    }
}

The JSON response looks like this:

{
  "Payload": "{\"UserName\":\"Marco Uzcátegui\",\"Clients\":[{\"UserProfileId\":4,\"ProfileName\":\"Platform Administrator\",\"ClientName\":\"Smart Hotel Platform\",\"InSession\":true},{\"UserProfileId\":5,\"ProfileName\":\"Administrator\",\"ClientName\":\"La Moncloa de San Lázaro\",\"InSession\":false},{\"UserProfileId\":6,\"ProfileName\":\"Administrator\",\"ClientName\":\"Jardín Tecina\",\"InSession\":false}]}",
  "StatusCode": "424",
  "StatusDescription": null
}

As you can see, I have a escaped string inside "Payload" that is a correct JSON, so I want to generate another NSMutableDictionary with that string, so I'm doing this:

NSData *tPayloadData = [tPayload dataUsingEncoding:NSUTF8StringEncoding];
if ([NSJSONSerialization isValidJSONObject:tPayloadData]) {
    _Payload = [NSJSONSerialization JSONObjectWithData:tPayloadData options:kNilOptions error:nil];
    _RowCount = _Payload.count;
} else {
    NSLog(@"JSON Wrong String %@",tPayload);
}

So I'm creating an NSData from the NSString and asking if is valid, it always returns false.

I have tried to replace the "\" from the string and is not working.

[tPayload stringByReplacingOccurrencesOfString:@"\\\"" withString:@""]

I have tried to create a NSMutableDictionary with the string, but the result is not a dictionary.

NSMutableDictionary *tPayload = [tJSONResponse objectForKey:@"Payload"];

I'm kind of lost here.

Any help will be appreciated.

Regards.

Upvotes: 0

Views: 827

Answers (2)

vadian
vadian

Reputation: 285069

The issue is this line

[NSJSONSerialization isValidJSONObject:tPayloadData]

From the documentation of isValidJSONObject

Returns a Boolean value that indicates whether a given object can be converted to JSON data.

given object means an NSArray or NSDictionary but not NSData

Remove that check and implement the error parameter in JSONObjectWithDataoptions:error:

Upvotes: 1

Codo
Codo

Reputation: 78825

The method NSJSONSerialization.isValidJSONObject: checks if an object (e.g. a NSDictonary or NSArray instance) can be converted to JSON. It doesn't check if a NSData instance can be converted from JSON. For NSData, it will always return false.

So just call NSJSONSerialization.JSONObjectWithData:options: and check the result instead.

Upvotes: 1

Related Questions