我在将JSON
元素转换为NSData
时遇到了问题,并且NSData
变量在Swift中转换回JSON
。
首先,我想提取以下JSON数据的encryptedData
元素:
{
"transactionID" : 12345,
"encryptedData" : [-67,51,-38,61,-72,102,48]
}
进入NSData encryptedData
变量,但似乎无法做到。我使用SwiftyJSON
解析JSON
,如下所示:
let list: Array<JSON> = json["encryptedData"].arrayValue!
但是这给了我一个ScalarNumber数组,我不知道如何存储到NSData
对象中。
其次,我想从同一个JSON
对象生成NSData
:
let jsonObject = [
"transactionID" : 12345,
"encryptedData" : encryptedData
]
但是NSData encryptedData
对象没有被转换为[-67,51,-38,61,-72,102,48],它似乎只是使JSON字符串无效。
有什么想法吗?
答案 0 :(得分:21)
以下是在swift 2.0中转换JSON和NSData的代码(改编自Shuo的回答)
// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
} catch let myJSONError {
print(myJSONError)
}
return nil
}
// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
do {
return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
} catch let myJSONError {
print(myJSONError)
}
return nil;
}
答案 1 :(得分:18)
在SwiftyJSON中,您可以使用rawData方法获取NSData:
if let encryptedData:NSData = json["encryptedData"].rawData() {
NSLog(NSString(data: encryptedData, encoding: NSUTF8StringEncoding)!)
}
要生成JSON,您应该将数据转换为数组对象:
if let encryptedDataArray = JSON(data: encryptedData).arrayObject {
let jsonObject:JSON = [
"transactionID" : 12345,
"encryptedData" : encryptedDataArray
]
NSLog(NSString(data: jsonObject.rawData()!, encoding: NSUTF8StringEncoding)!)
}
答案 2 :(得分:12)
我对SwiftyJSON一无所知。我使用以下代码片段在json和nsdata
之间进行转换// Convert from NSData to json object
public class func nsdataToJSON(data: NSData) -> AnyObject? {
return NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil)
}
// Convert from JSON to nsdata
public class func jsonToNSData(json: AnyObject) -> NSData?{
return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}
答案 3 :(得分:7)
@Sunil Targe这里是Swift3版本。希望这可以帮助。 (改编自Ciprian Rarau的回答)
将数据转换为JSON
func dataToJSON(data: Data) -> Any? {
do {
return try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
} catch let myJSONError {
print(myJSONError)
}
return nil
}
从JSON转换为数据
func jsonToData(json: Any) -> Data? {
do {
return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
} catch let myJSONError {
print(myJSONError)
}
return nil;
}
答案 4 :(得分:3)
Swift 4对我有用:
// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
do {
return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData
} catch let myJSONError {
print(myJSONError)
}
return nil;
}
答案 5 :(得分:2)
class ViewController: UIViewController {
let requestURL : NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
let session = URLSession.shared
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
func fetchData()
{
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if(statusCode == 200)
{
do {
let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
print(jsonResponse as! NSDictionary)
}
catch let error
{
print(error)
}
}
}
task.resume()
}
}
答案 6 :(得分:1)
Swift 5 和 SwiftyJSON 对我有用:
import SwiftyJSON
func getDataFrom(JSON json: JSON) -> Data? {
do {
return try json.rawData(options: .prettyPrinted)
} catch _ {
return nil
}
}
func getJSONFrom(Data data: Data) -> JSON? {
do {
return try JSON(data: data, options: .mutableContainers)
} catch _ {
return nil
}
}