2016-01-22 29 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