从 NSDictionary iPhone 创建 JSON 对象



我想创建一个 JSON 字符串,如下所示

{
    "veneue": {
        "clientId": "b",
        "name": "d",
        "tagline": "f",
        "phone": "b",
        "address": "d",
        "city": "f",
        "state": "b",
        "zip": "d",
        "twitter": "f",
        "license": "d",
        "imagePath": "f",
        "pickupLocation": "b"
    },
    "drinks": [
        {
            "type": "d",
            "name": "f",
            "servingTable": {
                "servingSize": "b",
                "price": "d"
            }
        },
        {
            "type": "d",
            "name": "f",
            "servingTable": {
                "servingSize": "b",
                "price": "d"
            }
        }
    ]
}

这是我的模型

JSON

字符串应包含两个 JSON 格式,venue, drinks .

场地具有下面列出的子对象作为 venueDictionary。其中,作为饮料是模型DrinkClass的数组

NSDictionary *venueDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                               @"name"   ,@"xx"//[self.nameVenue text],
                               @"tagLine",@"xx"//[self.taglineVenue text],
                               @"phone"  ,@"xx"//[self.phoneVenue text],
                               @"addres" ,@"xx"//[self.addressVenue text],
                               @"city"   ,@"xx"//[self.cityVenue text],
                               @"state"  ,@"xx"//[self.stateVenue text],
                               @"zip"    ,@"xx"//[self.zipVenue text],
                               @"twitter",@"xx"//[self.twitterVenue text],
                               @"license",@"xx"//[self.licenseVenue text],
                               @"pickUpLocation",@"xx"//[self.pickUpVenue text],
                               @"imagePath",randomImageName,
                               nil];
arrayDrinks = [[NSMutableArray alloc] init]; //SUPPOSE THIS IS DRINK ARRAY

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                      @"venue", venueDictionary,
                      @"drinks",
                      nil];

1-如何将其添加到@"饮料"以创建JSON 如上所述,其次我正在使用 SBJSONWriter ,如何使用 JSON 词典创建字符串。

//SBJsonWriter *writer = [[SBJsonWriter alloc] init];

你对dictionaryWithObjectsAndKeys的每次调用,你都以错误的方式提供参数(你把键设置为值,反之亦然)。

只需将arrayDrinks添加为@"drinks"键的值即可。

只需将jsonDictionary作为要序列化的对象传递(到 stringWithObject: )。

正如@Wain所说,您以错误的方式传递值。 要从您的 jsonDictonary 创建 JSON,请使用这个

#import "SBJsonWriter.h"
...
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonString = [jsonWriter stringWithObject:jsonDictionary];  
[jsonWriter release];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSError *error = nil;
NSArray *jsonObjects = [jsonParser objectWithString:jsonString error:&error];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
NSArray *sorted = [jsonObjects sortedArrayUsingDescriptors:@[sort]];

最新更新