1

我想创建一个 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 字符串应包含两个 JSONObject venue, drinks,.

Venue 有下面列出的子对象,如venueDictionary。其中作为 Drinks 是一个模型的数组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-如何将它添加到@"drinks" 以创建 JSON 如上所述,其次我正在使用 SBJSONWriter ,如何使用 JSONDictionary 创建字符串。

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

3 回答 3

2

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

只需添加arrayDrinks作为@"drinks"键的值。

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

于 2013-10-21T14:34:15.187 回答
2

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

#import "SBJsonWriter.h"

...

SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];

NSString *jsonString = [jsonWriter stringWithObject:jsonDictionary];  

[jsonWriter release];
于 2013-10-21T14:41:35.387 回答
0
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]];
于 2013-11-01T07:36:40.040 回答