2015-10-04 85 views
1

轉換NSString適當的JSON格式..轉換的NSString適當的JSON格式

NSString *input_json = [NSString stringWithFormat:@"{\"id\":\"%@\",\"seconds\":\"%d\",\"buttons\": \"%@\"}", reco_id, interactionTime, json_Buttons]; 

這裏json_Button在從NSDictionary的轉換JSON格式..

我input_json結果是:

 
{"id":"119","seconds":"10","buttons": "{ 
    "update" : "2", 
    "scan" : "4" 
}"} 

它的格式不正確。按鍵包含「{}」我想刪除這些引號。

預期的結果是:

 
{ 
    "id": "119", 
    "seconds": "10", 
    "buttons": { 
     "update": "2", 
     "scan": "4" 
    } 
} 

回答

2

你會對此完全錯誤的。首先,創建一個包含要轉換爲JSON的所有數據的NSDictionary。然後使用NSJSONSerialization將字典正確地轉換爲JSON。

像這樣將工作:

NSDictionary *dictionary = @{ @"id" : reco_id, @"seconds" : @(interactionTime), @"buttons" : json_Buttons }; 
NSError *error = nil; 
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error]; 
if (data) { 
    NSString *jsonString = [[NSString alloc] intWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"JSON: %@", jsonString); 
} else { 
    NSLog(@"Unable to convert dictionary to JSON: %@", error); 
} 
+0

嗨rmaddy ..感謝您的回覆.. –

+0

嗨rmaddy得到有效的JSON ..但我的服務器不接受...您的建議給出了這樣的結果.. JSON:{ 「ID」:「119」 , 「seconds」:10, 「buttons」:「{\ n \」update \「:\」2 \「,\ n \」scan \「:\」4 \「\ n}」 }服務器期望,「按鈕」:{「更新」:「2」,「掃描」:「4」}像這樣...意味着按鈕鍵值不應該在「」..你能幫我嗎.. –

+0

這是一個完全不同的問題。你應該在這個問題上發佈一個新問題。一定要包括相關的細節 – rmaddy

0

這是一個壞主意,嘗試手動構建JSON字符串。使用NSJSONSerialization類。這很容易。創建你的字典,然後致電dataWithJSONObject:options:error:

如果使用選項:NSJSONWritingPrettyPrinted它會插入換行符和空格,使JSON更具可讀性。

通過使用該函數,您每次都可以正確格式化JSON,並且它非常靈活,因爲如果您向其發送不同的字典,就會得到不同的JSON。

+0

嗨,感謝您的回覆...嗨,這裏是我的json_Buttons值...{「update」:「2」,「scan」:「4」}當我把所有的值放入nsdictionary中時,它會像這樣插入字典。,,,, {buttons =「{\ n \」update \「: 「2 \」,\ n \「scan \」:\「4 \」\ n}「; id = 119;秒= 10; }我不希望我的按鈕值在字符串「{}」之內。 –

+0

因此編輯您的問題以顯示生成此JSON的代碼。 –