Question

I want to format a JSON string of below format using NSJSONSerialization:

{
"data":{"userName":"rrullo","password":"rrullo!"},
"meta":{"appId":"S3B9CU4R2B9JTXV9254Y","appVersion":"2.1.0","serverVersion":"1.1.0","platform":"iOS","deviceToken":"1234","tm_session_id":"BB0000001234"}
}

But I have no clue how to achieve this format though. Can someone help me please ......

Was it helpful?

Solution

First fill two NSDictionaries with your 'meta' and 'data' info. Then add those into a main NSDictionary and then serialize using NSJsonSerialization

NSDictionary * metaDict = [[NSDictionary alloc] initWithObjectsAndKeys: 
@"appId", @"S3B9CU4R2B9JTXV9254Y", @"appVersion", @"2.1.0", @"serverVersion", @"1.1.0", @"platform", @"iOS",..., nil];

NSDictionary * dataDict = [[NSDictionary alloc] initWithObjectsAndKeys: 
@"userName", @"rrullo", @"password", @"rrullo!", nil];

NSDictionary * mainDict = [[NSDictionary alloc] initWithObjectsAndKeys: 
@"data", dataDict, @"meta", metaDict, nil];

Now you can use NSJsonSerialization to convert that mainDict to a NSString

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mainDict 
                                                   options:NSJSONWritingPrettyPrinted 
                                                     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData  encoding:NSUTF8StringEncoding];

Hope this helps

OTHER TIPS

NSDictionary dictData = @{ @"UserName":@"rrullo", @"password":@"rrullo!"};
NSDictionary dictMeta = @{ @"appId":@"S3B9CU4R2B9JTXV9254Y", etc};
NSDictionary dictJSON = @{ @"data":dictData, @"meta":dictMeta };

NSError *error = nil; 
NSData *dataJSON = [NSJSONSerialization dataWithJSONObject:dictJSON 
                                                   options:NSJSONWritingPrettyPrinted 
                                                     error:&error];
if (!error) {
    NSString *jsonString = [[NSString alloc] initWithData:dataJSON encoding:NSUTF8StringEncoding];
} else {
    NSLog(@"Error: %@", error);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top