我有dictionary
我需要使用JSON string
生成dictionary
。有可能转换它吗?你能帮忙吗?
答案 0 :(得分:728)
Apple在iOS 5.0和Mac OS X 10.7中添加了JSON解析器和序列化程序。请参阅NSJSONSerialization。
要从NSDictionary或NSArray生成JSON字符串,您不再需要导入任何第三方框架。
以下是如何操作:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 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];
}
答案 1 :(得分:222)
以下是NSArray和NSDictionary的类别,使这非常容易。我添加了一个漂亮的打印选项(新行和标签,以便于阅读)。
@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end
@implementation NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"{}";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end
@implementation NSArray (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"[]";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
答案 2 :(得分:59)
将NSDictionary转换为NSString:
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
答案 3 :(得分:35)
注意:此答案是在iOS 5发布之前给出的。
获取json-framework并执行此操作:
#import "SBJsonWriter.h"
...
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonString = [jsonWriter stringWithObject:myDictionary];
[jsonWriter release];
myDictionary
将是您的字典。
答案 4 :(得分:23)
您也可以通过在调试器中输入以下内容来实时执行此操作
po [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:yourDictionary options:1 error:nil] encoding:4];
答案 5 :(得分:13)
您可以传递数组或字典。在这里,我正在使用NSMutableDictionary。
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"a" forKey:@"b"];
[contentDictionary setValue:@"c" forKey:@"d"];
要从NSDictionary或NSArray生成JSON字符串,您无需导入任何第三方框架。只需使用以下代码: -
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contentDictionary // Here you can pass array or dictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString;
if (jsonData) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//This is your JSON String
//NSUTF8StringEncoding encodes special characters using an escaping scheme
} else {
NSLog(@"Got an error: %@", error);
jsonString = @"";
}
NSLog(@"Your JSON String is %@", jsonString);
答案 6 :(得分:12)
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"a" forKey:@"b"];
[contentDictionary setValue:@"c" forKey:@"d"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
答案 7 :(得分:7)
在 Swift(版本2.0):
class func jsonStringWithJSONObject(jsonObject: AnyObject) throws -> String? {
let data: NSData? = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)
var jsonStr: String?
if data != nil {
jsonStr = String(data: data!, encoding: NSUTF8StringEncoding)
}
return jsonStr
}
答案 8 :(得分:3)
现在不需要第三方课程ios 5引入了Nsjsonserialization
NSString *urlString=@"Your url";
NSString *urlUTF8 = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[[NSURL alloc]initWithString:urlUTF8];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:&myError];
Nslog(@"%@",res);
此代码可用于获取jsondata。
答案 9 :(得分:1)
至于ISO7,至少可以使用NSJSONSerialization轻松完成此操作。
答案 10 :(得分:1)
在Swift中,我创建了以下辅助函数:
|-------------|
| header |
|-------------|
| |
| main |
| |
| |
|-------------|
| footer |
|-------------|
答案 11 :(得分:1)
这是 Swift 4 版本
extension NSDictionary{
func toString() throws -> String? {
do {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String(data: data, encoding: .utf8)
}
catch (let error){
throw error
}
}
}
用法示例
do{
let jsonString = try dic.toString()
}
catch( let error){
print(error.localizedDescription)
}
或者,如果您确定它是有效的字典,那么您可以使用
let jsonString = try? dic.toString()
答案 12 :(得分:0)
这将在swift4和swift5中工作。
let dataDict = "the dictionary you want to convert in jsonString"
let jsonData = try! JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
print(jsonString)
答案 13 :(得分:-1)
<div ng-repeat="fruit in fruits">
<input type="checkbox" name="{{fruit.name}} ng-model="fruit.value"
ng-click="isChecked(fruit)" required>{{fruit.name}}
</div>
<input type="hidden" ng-model="selectedFruits">
这个非常接近原始的Objective-C打印样式