2013-10-21 37 views
1

创建一个JSON对象,我想创建一个JSON字符串如下从NSDictionary的iPhone

{ 
    "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字符串应该包含两个一个JSONObjects,venue, drinks

地点具有如venueDictionary下面列出的子对象。 其中饮品是Model 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的阵列,如何创建JSONDictionary字符串。

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

回答

2

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

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

只需通过jsonDictionary作为对象被序列化(到stringWithObject:)。

2

正如@Wain说你逝去的值在错误的道路。并从你的jsonDictonary创建JSON使用这个

#import "SBJsonWriter.h" 

... 

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

NSString *jsonString = [jsonWriter stringWithObject:jsonDictionary]; 

[jsonWriter release]; 
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]];