0

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 ......

4

2 回答 2

2

首先用你的“元”和“数据”信息填充两个 NSDictionaries。然后将它们添加到主 NSDictionary 中,然后使用 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];

现在您可以使用 NSJsonSerialization 将该 mainDict 转换为 NSString

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

希望这可以帮助

于 2013-10-10T17:04:18.453 回答
2
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);
}
于 2013-10-10T17:17:27.833 回答