JSONKit:创建一个json格式的字符串

时间:2011-07-18 16:29:43

标签: ios json

我想将NSDictionary和NSArrays转换为json格式。 JSON Kit可以做到这一点吗?

2 个答案:

答案 0 :(得分:9)

// data-> string

NSMutableDictionary *nameElements = [NSMutableDictionary dictionary];     

[nameElements setObject:@"abcd" forKey:@"username"];

[nameElements setObject:@"1234" forKey:@"password"];    

NSString* jsonString = [nameElements JSONString];  

// string-> data

NSDictionary *nameElements_ = [jsonString objectFromJSONString];   

for(NSString *key in [nameElements_ allKeys]) {
    NSString* body = [nameElements_ objectForKey:key];
    NSLog(@"%@", body);
}

答案 1 :(得分:2)

这是一个向服务器发送字典和数组的示例。这对我来说是1000000%。

SBJSON *jparser = [[SBJSON new] autorelease];


NSString *ArrayjsonItems = [jparser stringWithObject:self.UrMergedArray];

NSString *DicjsonItems = [jparser stringWithObject:self.UrMergedDic];




NSLog(@"array Items :%@",self.UrMergedArray);

NSLog(@"dic Items :%@",self.UrMergedDic);




NSString *postString =[NSString stringWithFormat:@"Arrayitems=%@&Dicitems=%@",ArrayjsonItems,DicjsonItems];


NSLog(@"it is going to post : %@ \n\n",postString);



NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:snapURL];

[request setHTTPMethod:@"POST"];

[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];



NSURLConnection *connection=[[NSURLConnection alloc]
                             initWithRequest:request
                             delegate:self];


if (connection) {

    self.receivedData = [[NSMutableData data] retain];

}


[connection release];