swift里 怎么把字典或者数组转json字符串

2025-01-31 23:56:23
推荐回答(1个)
回答1:

您好,很高兴为您解答,方法好下:
+(NSString *)stringTOjson:(id)temps //把字典和数组转换成json字符串
{
NSData* jsonData =[NSJSONSerialization dataWithJSONObject:temps
options:NSJSONWritingPrettyPrinted error:nil];
NSString *strs=[[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
return strs;
}

利用NSJSONSerialization序列化成NSData,再通过NSString 转成JSON字符串
func toJSONString(dict:NSDictionary!)->NSString{

var data = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
var strJson=NSString(data: data, encoding: NSUTF8StringEncoding)
return strJson

}