2012-08-13 27 views
15
NSData* jsonDataToSendTheServer; 

NSDictionary *setUser = [NSDictionary 
      dictionaryWithObjectsAndKeys:[@"u" stringByAppendingString:my.id],@"id", 
             @"GET_USER_INFO",@"command", 
             @"",@"value", 
             nil]; 


NSDictionary *setUser = [NSDictionary 
      dictionaryWithObjectsAndKeys:[@"u" stringByAppendingString:my.id],@"id", 
             @"GET_USER_INFO",@"command", 
             @"",@"value", 
             nil]; 

NSLog(@"%@", jsonDataToSendTheServer); 

這是我的代碼。當我跑上面的代碼,我得到這個打印如何在objective-c中創建json

<7b226964 223a2275 35383738 37373334 31222c22 636f6d6d 616e6422 3a224745 545f5553 45525f49 4e464f22 2c227661 6c756522 3a22227d> 

我不知道我是否可以創建一個json或不。

我該如何解決這個問題?

回答

6

你可以試試下面創建JSON:

NSArray *objects=[[NSArray alloc]initWithObjects:objects here,nil]; 
NSArray *keys=[[NSArray alloc]initWithObjects:corresponding keys of objects,nil]; 
NSDictionary *dict=[NSDictionary dictionaryWithObjects:objects forKeys:keys]; 
NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; 

這個工作完全在我的情況

3

試試下面

NSDictionary *o1 = [NSDictionary dictionaryWithObjectsAndKeys: 
@"ABCD", @"key1", 
@"EFG", @"key2", 
nil]; 

NSDictionary *o2 = [NSDictionary dictionaryWithObjectsAndKeys: 
@"XYZ", @"key1", 
@"POI", @"key2", 
nil]; 

NSArray *array = [NSArray arrayWithObjects:o1, o2, nil]; 

NSString *jsonString = [array JSONRepresentation]; 

//發送jsonString服務器 執行上面的代碼後,jsonString包含:

[ 
    { 
     "key1": "ABCD", 
     "key2": "EFG" 
    }, 
    { 
     "key1": "XYZ", 
     "key2": "POI" 
    } 
] 
+3

JSONRepresentation是第三方庫的一部分,除非我失去了一些東西,這不是一個有效的答案。 – Artemix 2016-10-07 14:07:16

-2

NSMutableString * mutableString = nil; NSString * string = @「」;

@try 
{ 
    if (mutableString == nil) 
    { 
     mutableString = [[NSMutableString alloc] init]; 
    } 

    [mutableString appendFormat:@"{"]; 
    [mutableString appendFormat:@"\"string1\":%@"",",@""]; 
    [mutableString appendFormat:@"\"string2\":\"%@\"",@""]; 
    [mutableString appendFormat:@"}"]; 
    jsonString = mutableString ; 
} 
@catch (NSException *exception) 
{ 

} 
@finally 
{ 
    return string; 
} 
0

試試這個

NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://api.iospond.com/api/index.php/GetData"]]; 
    NSError *error=nil; 
    id response=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; 
    NSLog(@"Your JSON Object: %@ Or Error is: %@", response, error);