使用 nsmutabledictionary 创建嵌套的 JSON 字符串
Posted
技术标签:
【中文标题】使用 nsmutabledictionary 创建嵌套的 JSON 字符串【英文标题】:Creating nested JSON string using nsmutabledictionary 【发布时间】:2013-10-27 03:47:30 【问题描述】:我正在尝试创建以下格式的 json 字符串:
"cat_id" : 4992,
"brand" : "Toshiba",
"weight" : "gte":1000000, "lt":1500000 ,
"sitedetails" :
"name" : "newegg.com",
"latestoffers" :
"currency": "USD",
"price" : "gte" : 100
我使用了以下方法来生成这个:
-(void)queryBuilderWithObj:(NSString *)object andKeyValue:(NSString *)key
NSLog(@"object %@ and key %@",object,key);
if([key rangeOfString:@","].location == NSNotFound)
[querybuild setObject:object forKey:key];
else
NSArray *tempArray = [key componentsSeparatedByString:@","];
int index = tempArray.count - 1;
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
while (index)
if (index == tempArray.count - 1)
if([querybuild objectForKey:[tempArray objectAtIndex:index]])
NSMutableArray *objArray = [[NSMutableArray alloc] init];
[objArray addObject:[querybuild objectForKey:[tempArray objectAtIndex:index]]];
[objArray addObject:object];
[tempDict setObject:objArray forKey:[tempArray objectAtIndex:index]];
else
[tempDict setObject:object forKey:[tempArray objectAtIndex:index]];
else
if([querybuild objectForKey:[tempArray objectAtIndex:index]])
NSMutableArray *objArray = [[NSMutableArray alloc] init];
[objArray addObject:[querybuild objectForKey:[tempArray objectAtIndex:index]]];
NSMutableDictionary *subDict = [[NSMutableDictionary alloc] init];
[subDict setDictionary:tempDict];
[objArray addObject:subDict];
[tempDict setObject:objArray forKey:[tempArray objectAtIndex:index]];
else
NSMutableDictionary *subDict = [[NSMutableDictionary alloc] init];
[subDict setDictionary:tempDict];
[tempDict setObject:subDict forKey:[tempArray objectAtIndex:index]];
index --;
[querybuild setObject:tempDict forKey:[tempArray objectAtIndex:0]];
NSLog(@"querybuild %@ ",querybuild);
最后生成的nsmutabledictionary是:
querybuild
brand = Toshiba;
"cat_id" = 4992;
sitedetails =
gte = 100;
latestoffers =
gte = 100;
price =
gte = 100;
;
;
price =
gte = 100;
;
;
weight =
lt = 1500000;
;
我传递的对象和密钥如下:
[sem queryBuilderWithObj:@"4992" andKeyValue:@"cat_id" ];
[sem queryBuilderWithObj:@"Toshiba" andKeyValue:@"brand"];
[sem queryBuilderWithObj:@"1000000" andKeyValue:@"weight,gte"];
[sem queryBuilderWithObj:@"1500000" andKeyValue:@"weight,lt"];
[sem queryBuilderWithObj:@"newegg.com"andKeyValue:@"sitedetails,name" ];
[sem queryBuilderWithObj:@"USD" andKeyValue:@"sitedetails,latestoffers,currency"];
[sem queryBuilderWithObj:@"100" andKeyValue:@"sitedetails,latestoffers,price,gte"];
知道如何生成所需的输出吗? querybuild 是在这个方法中声明为类变量的 nsmutabledictionary 对象吗?
【问题讨论】:
【参考方案1】:如果你想要这个最好的方法是创建更多的字典示例:
NSMutableDictionary *json= [[NSMutableDictionary alloc] init];
[json setObject:@"4992" forKey:@"cat_id"];
[json setObject:@"Toshiba" forKey:@"brand"];
//create weight object
NSMutableDictionary *weight= [[NSMutableDictionary alloc] init];
[weight setObject:@"1000000" forKey:@"gte"];
[weight setObject:@"1500000" forKey:@"lt"];
//attach the object
[json setObject:weight forKey:@"weight"];
//create sitedetails objects
NSMutableDictionary *sitedetails= [[NSMutableDictionary alloc] init];
[sitedetails setObject:@"newegg.com" forKey:@"name"];
//create latestoffers objects
NSMutableDictionary *latestoffers= [[NSMutableDictionary alloc] init];
[latestoffers setObject:@"USD" forKey:@"currency"];
//new dictionary for price
[sitedetails setObject:latestoffers forKey:@"latestoffers"];
[json setObject:sitedetails forKey:@"sitedetails"];
NSLog(@"%@",json);
可以在json字符串中转换字典后...
-(NSString*)getJsonStringByDictionary:(NSDictionary*)dictionary
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:&error];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
【讨论】:
字典生成的能不能更简单一些?【参考方案2】:使用新的Objective-C语法和NSJSONSerialization
,正如其他人所指出的,这可以很好地完成:
NSDictionary *latestprice = @@"gte": @100;
NSDictionary *latest = @@"currency": @"USD", @"price": latestprice;
NSDictionary *details = @@"name": @"newegg.com", @"latestoffers": latest;
NSDictionary *weight = @@"gte": @1000000, @"lt": @1500000;
NSDictionary *json = @
@"cat_id": @4992,
@"brand": @"Toshiba",
@"weight": weight,
@"sitedetails": details
;
NSData *data = [NSJSONSerialization dataWithJSONObject:json
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
我不知道您的 querybuild 是什么,但如果它是字典,您可以根据需要提取数据。或者您是否需要根据 querybuild 中的键动态创建此结构?
【讨论】:
应该动态完成。访问对象的对象(可以是字典) 在这种情况下,您走在正确的轨道上,只需创建一个NSMutableDictionary
并在逗号处拆分键后将值粘贴在那里,当您遇到键中的逗号时递归地创建更多字典。 【参考方案3】:
您是否尝试过使用 NSJSONSerialization 类的 JSONObjectWithData:options:error:
?
它还具有一个方便的isValidJSONObject
方法,您可以使用它来帮助您调试您尝试转换的结构。
【讨论】:
【参考方案4】:没必要。只需使用内置的NSJSONSerialization
,因为这就是它的用途。它将JSON
对象放入NSDictionaries
或NSArrays
。
这是你如何使用它:
//This part is just to download the data. If you're using another method - that's fine. Just make sure that the download is in NSData format
NSURL *url = [[NSURL alloc] initWithString : @"YOUR_URL_HERE"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL : url];
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
//This is the actual NSJSONSerialization part.
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableLeaves
error:nil];
现在您可以像这样访问NSDictionary
中的元素:
NSString *cat_id = [jsonDict objectForKey : @"cat_id"];
中的那些对象是NSDictionaries
- 嵌套对象。
它们可以像这样访问:
NSDictionary *slidedetailsDict = [jsonDict objectForKey : @"slidedetails"];
NSString *name = [slidedetailsDict objectForKey : @"name"];
【讨论】:
你明白这个问题吗?我正在尝试创建该特定模式的 JSON 字符串?它与创建任何 JSON 字符串或访问对象无关。 我明白了。但关键是NSJSONSerialization
是这里的最佳选择。如果要创建自定义对象,请创建自定义类并将其属性设置为 JSON 数据的各个部分。
但它适用于我输入对象和键的方式吗?
因为 querybuild 是 NSMutableDictionary
对象 - 当然可以!一旦您获得NSDictionary
格式的 JSON 数据,这将是基本的。
问题的重点是如何通过循环和条件构建 NSMutableDictionary 数据,以便我可以转换为 JSON 字符串以上是关于使用 nsmutabledictionary 创建嵌套的 JSON 字符串的主要内容,如果未能解决你的问题,请参考以下文章
如何获得 NSDictionary/NSMutableDictionary 的原始顺序?
NSMutableDictionary 没有得到预期的输出。
创建一个包含多个 NSMutableDictionary 对象的 NSMutableArray