2012-09-17 33 views
2

如何用NSDataObjective C中創建json對象。我的值是NSData變量。如何在Objective C中使用NSData創建json對象?

+0

你想發送NSData,或者從中獲取值,然後從中創建你的JSON,然後發送 –

+0

@VakulSaini: - ys我試過並找到了一個函數NSJSONSerialization。但是當我試圖插入NSData到它,我得到了一個錯誤..你可以請幫我找出一個更好的解決方案.. –

+0

好吧,看看我的答案吧。 – TheTiger

回答

2

,如果你有NSData對象的值,那麼你可以把它轉換成的NSString變量像波紋管

NSString *response = [[NSString alloc] initWithData:receivedData 
               encoding:NSUTF8StringEncoding]; 

編輯...

我不知道你想要什麼,但我給你從像波紋管串JSON數組..

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
    [responseData release]; 

    NSError *error; 
    SBJSON *json = [[SBJSON new] autorelease]; 
    NSArray *arrData = [json objectWithString:responseString error:&error]; 
    [responseString release]; 

您可以在陣列

獲取數據

希望這個幫你隊友...

:)

+0

是我試圖將NSData轉換爲NSString。但它總是返回nul。也害怕將它轉換成bcos它可能會導致數據丟失。 現在NSData變量持有IV,SALT和CIPHERTEXT。我將這三個值連接到一個名爲encryptedData的變量。 (NSData * encryptedData;)。現在我想創建一個可以容納encryptedData的json ..任何幫助? –

3

可以在iOS 5中使用這樣的(如果你確信你的JSON結構,你可以直接使用NSArrayNSDictionary做投)

NSError *jsonError; 
id jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:myData options:NULL error:&jsonError]; 
if(jsonError) { 
    // check the error description 
    NSLog(@"json error : %@", [jsonError localizedDescription]); 
} else { 
    // use the jsonDictionaryOrArray 
} 
+0

嗨Moxy,是iPhone開發新手,我很困惑。你可以告訴我的代碼做同樣的.. –

+0

這行代碼應該足以讓你的JSON對象。你不明白的是什麼?你已經知道你的json是如何格式化的? – Moxy

+0

但是,當打印jsonDictionaryOrArray(NSLog(@「%@」,jsonDictionaryOrArray);)的值時,它顯示爲nil。你知道爲什麼嗎? –

1
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"youur link"]]; 
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil]; 
if([jsonObjects isKindOfClass:[NSArray class]]){ 
    //Is array 
}else if([jsonObjects isKindOfClass:[NSDictionary class]]){ 
    //is dictionary 
}else{ 
    //is something else 
} 

編輯SWIFT

do { 
     if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>] { 

     } else { 
      print("bad json") 
     } 
    } catch let error as NSError { 
     print(error) 
    }