【问题标题】:Create a JsonString in iOS在 iOS 中创建 JsonString
【发布时间】:2012-08-09 11:44:38
【问题描述】:

我是 iOS 新手。我像这样创建了JSON NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"User", @"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:@"Ali", @"2020", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

然后我可以通过两种机制将其转换为NSString

1)

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];

NSString *jsonString = nil;
if (! jsonData) {
     NSLog(@"Got an error: %@", error);
} else {
     jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

2)

NSString *jsonString = [jsonDictionary JSONRepresentation];

第二种方式我得到这个warning

Instance method '-JSONRepresentation' not found (return type defaults to 'id')

但是当我运行项目时,两种机制都可以正常工作:

NSLog(@"Val of json parse obj is %@",jsonString); 

您知道如何以第二种方式删除警告吗?

我的主要目标是 POST 使用 RESTful Web 服务将此 json 字符串发送到外部数据库。 基本上考虑到我的主要目标,哪种方式更好?

【问题讨论】:

    标签: iphone objective-c ios xcode


    【解决方案1】:

    您应该使用NSJSONSerialization,因为它速度更快,并且直接与 iOS SDK 一起提供,只要您的“目标受众”是 iOS5+

    要将数据发布到您的网络服务,您需要按照这些方式创建一个请求...

    NSDictionary * postDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"value1", @"value2", nil]
                                                                      forKeys:[NSArray arrayWithObjects:@"key1", @"key2", nil]];
    
    NSError * error = nil;
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONReadingMutableContainers error:&error];
    
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"your_webservice_post_url"]];
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:jsonData];
    
    NSURLConnection * myConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
    

    请阅读NSURLConnectionDelegate 协议。

    【讨论】:

    • 我使用了代码,但没有发布到我的外部数据库。我尝试了12,但它们也不起作用。你能猜出是什么问题吗?我可以成功连接数据库和 GET 但不能 POST
    • 您是否对上述请求执行了某种类型的连接? [你不应该使用同步连接,除非有充分的理由,但出于这个目的] - [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error: &error];
    • 我更新了答案以在其中显示 NSURLConnection。有更好的方法来实现这种连接,但这超出了这个问题的范围。
    • 这正是我通过第二个链接所做的。但你是对的,我可能会提出一个新问题。
    【解决方案2】:

    对于 iOS 5.0 >

    像这样使用NSJSONSerialization

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
     NSLog(@"jsonData as string:\n%@ Error:%@", resultAsString,error);
    

    对于

    使用json-framework第三方库,使用NSDictionary的类别来提供json字符串:

     NSString *jsonString = [dictionary JSONRepresentation];
    
     //with options
     NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil]
    

    【讨论】:

    • 这正是我对JSONRepresentation所做的。看看我的问题。考虑到我的情况,哪一个更好?
    • 还有我在JSONRepresentation上的warning
    • 最好使用 NSJSONSerialization
    • SBJSON 和 JSONKit 是第三方库。因此,要使用它们,您需要将它们添加到您的项目中。 NSJSONSerialization 在内置的苹果库中
    • 是的,我知道。我的情况如何(与 Web 服务 交谈)?请告诉我你的理由。
    【解决方案3】:

    【讨论】:

    • 这是另一种将Dictionary 转换为String 的机制。好的,但考虑到我的主要目标是与Web Service 交谈,哪个更好? :)
    • 我们可以使用NSJSONSerialization 代替SBJson。在我的情况下,哪一个更好?
    【解决方案4】:

    用这个方法希望对你有帮助

     NSArray *keys = [NSArray arrayWithObjects:@"User", @"Password", nil];
     NSArray *objects = [NSArray arrayWithObjects:@"Ali", @"2020", nil];
     NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
     NSError *error = nil;
     // NSError *error; 
     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
    
    
     id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    
     NSLog(@"\n\n\n id for json==%@ \n\n\n\n\n",result);
    

    【讨论】:

    • 请看我问题的结尾。考虑到我的主要目标,这种方式有什么用?
    【解决方案5】:
    JSON DEFAULT METHOD......
    
    +(NSDictionary *)stringWithUrl:(NSURL *)url postData:(NSData *)postData httpMethod:(NSString *)method { 
    
    NSDictionary *returnResponse=[[NSDictionary alloc]init];
    
    @try {
     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:180]; [urlRequest setHTTPMethod:method];
    
    if(postData != nil)
    {
        [urlRequest setHTTPBody:postData];
    }
    
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [urlRequest setValue:@"text/html" forHTTPHeaderField:@"Accept"];
    
    NSData *urlData;
    NSURLResponse *response;
    NSError *error;
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                    returningResponse:&response
                                                error:&error];
    returnResponse = [NSJSONSerialization
                      JSONObjectWithData:urlData
                      options:kNilOptions
                      error:&error];
    } @catch (NSException *exception) { returnResponse=nil; } @finally { return returnResponse; } }
    
    Return Method :
    
    +(NSDictionary )methodName:(NSString)string { 
    NSDictionary *returnResponse; NSData *postData = [NSData dataWithBytes:[string UTF8String] length:[string length]]; NSString *urlString = @"https//:..url...."; returnResponse=[self stringWithUrl:[NSURL URLWithString:urlString] postData:postData httpMethod:@"POST"];
    return returnResponse; 
    }
    

    【讨论】:

    • 您在多个问题上发布了此答案。请不要那样做。每个问题都应该按照自己的方式回答;如果答案相同,则应将其中一个问题标记为与另一个问题重复。当您有足够的声望时,您将能够投票这样做。
    猜你喜欢
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2015-05-27
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    相关资源
    最近更新 更多