2016-01-22 44 views
-4

下面是我的JSON字符串樣本格式:如何在ios中創建json?

{"entry":{"user":{"id":5,"name":"testuser"},"startday":"2015-12-27","status":"New","total":0.0,"entries":[{"id":752,"typename":{"id":3,"name":"teste"},"typetypeissue":{"id":4},"user":{"id":5,"name":"testuser 
"},"activity":{"id":8,"name":"Design"},"time":4.0,"comments":"","Date":"2015-12-27"},{"id":750,"typename":{"id":2,"name":"teste1"},"typeissue":{"id":13},"user":{"id":5,"name":"testuser 
"},"activity":{"id":8,"name":"Design"},"time":4.0,"comments":"","Date":"2015-12-29"}]}} 

的「項」部分比行值了。請幫助我如何創建一個json格式。用戶輸入的記錄數超過值「條目」部分。

+2

創建一個新的* * JSON!?以什麼方式*新*? – luk2302

+2

歡迎來到堆棧溢出!請閱讀[如何問好問題](// stackoverflow.com/help/how-to-ask)並嘗試編輯您的問題。有了高質量的問題,您將會收到更快的答案。謝謝! – SmokeDispenser

+0

NSString * string = @「這裏是你的json字符串」;如何以編程方式創建json字符串。 – Baskar

回答

2
NSString *string = @"here your JSON string"; 
NSData *stringData = [string dataUsingEncoding:NSUTF8StringEncoding]; 
id json = [NSJSONSerialization JSONObjectWithData:stringData 
              options:NSJSONReadingAllowFragments 
              error:nil]; 

UPDATE

您可以創建一個NSDictionary巫婆將有你的JSON的相同的結構,然後創建一個從這個字典,JSON表示的字符串

爲了從一個JSON字符串一個NSDictionary或NSArray,你不需要導入任何第三方框架了。

這裏是如何做到這一點:

NSDictionary *dictionaryOrArrayToOutput = // Here you will construct your dictionary 
NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput 
                options:NSJSONWritingPrettyPrinted // Pass kNilOptions if you don't care about the readability of the generated string 
                error:&error]; 

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

此代碼驗證json格式的字符串。我只能創建json sting。 – Baskar

+0

我真的不明白你想要做什麼 –

+0

我有這個問題。這裏是參考鏈接http://stackoverflow.com/questions/16057281/creating-json-format-in-objective-c – Baskar