如何在ios中创建json?

时间:2016-01-22 13:05:23

标签: ios objective-c

以下是我的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"}]}}

"条目" section超过行值。请帮我如何创建一个json格式。用户输入的值不仅仅是值"条目"部分。

1 个答案:

答案 0 :(得分:2)

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

<强>更新

您可以创建一个NSDictionary,它将具有与JSON相同的结构,然后使用JSON表示从该字典创建一个字符串

  

要从NSDictionary或NSArray生成JSON字符串,您不再需要导入任何第三方框架。

以下是如何操作:

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];
}