10

我正在尝试创建以下格式的 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 对象吗?

4

4 回答 4

12

如果你想要这个最好的方法是创建更多的字典示例:

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];
}
于 2013-10-29T10:47:19.420 回答
7

使用新的 Objective-C 语法and 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 中的键动态创建此结构?

于 2013-11-04T22:18:02.780 回答
2

您是否尝试过使用JSONObjectWithData:options:error:NSJSONSerialization 类?

它还具有一种方便的isValidJSONObject方法,可用于帮助您调试要转换的结构。

于 2013-10-27T03:58:59.273 回答
0

没必要。只需使用内置的,NSJSONSerialization因为这就是它的用途。它将JSON对象放入NSDictionariesor中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"];
于 2013-10-27T04:06:08.073 回答