在 Swift 中将 JSON 转换为 NSData,将 NSData 转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26840736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:37:41  来源:igfitidea点击:

Converting JSON to NSData, and NSData to JSON in Swift

jsonxcodeswiftnsdata

提问by John Smith

I'm having problems converting a JSONelement into NSData, and an NSDatavariable back into JSONin Swift.

我在将JSON元素转换为SwiftNSData并将NSData变量转换回JSONSwift 时遇到问题。

Firstly, I'd like to extract the encryptedDataelement of the following JSON data:

首先,我想提取encryptedData以下 JSON 数据的元素:

{
    "transactionID" : 12345,
    "encryptedData" : [-67,51,-38,61,-72,102,48]
}

into an NSData encryptedDatavariable but can't seem to be able to do it. I'm using SwiftyJSONto parse the JSONas follows:

进入 NSDataencryptedData变量,但似乎无法做到。我SwiftyJSON用来解析JSON如下:

let list: Array<JSON> = json["encryptedData"].arrayValue!

But this gives me an array of ScalarNumber which I don't know how to store into an NSDataobject.

但这给了我一个 ScalarNumber 数组,我不知道如何将其存储到NSData对象中。

Secondly, I'd like to generate JSONback from the same NSDataobject:

其次,我想JSON从同一个NSData对象生成:

let jsonObject = [
    "transactionID" : 12345,
    "encryptedData" : encryptedData
]

But the NSData encryptedDataobject doesn't get converted into [-67,51,-38,61,-72,102,48], it just seems to nullify the JSON string.

但是 NSDataencryptedData对象没有转换为 [-67,51,-38,61,-72,102,48],它似乎只是使 JSON 字符串无效。

Any ideas?

有任何想法吗?

采纳答案by Tish

In SwiftyJSON you can use rawData method to get NSData:

在 SwiftyJSON 中,您可以使用 rawData 方法来获取 NSData:

if let encryptedData:NSData = json["encryptedData"].rawData() {
    NSLog(NSString(data: encryptedData, encoding: NSUTF8StringEncoding)!)
}

To generate JSON as you want you should convert data to array object:

要根据需要生成 JSON,您应该将数据转换为数组对象:

if let encryptedDataArray = JSON(data: encryptedData).arrayObject {
    let jsonObject:JSON = [
        "transactionID" : 12345,
        "encryptedData" : encryptedDataArray
    ]
    NSLog(NSString(data: jsonObject.rawData()!, encoding: NSUTF8StringEncoding)!)
}

回答by Ciprian Rarau

Here is code to convert between JSON and NSData in swift 2.0 (adapted from Shuo's answer)

这是在 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;
}

回答by Shuo

I have no idea on SwiftyJSON. I use following code snippet to convert between json and nsdata

我不知道 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)
}

回答by FromTheStix

@Sunil Targe here is the Swift3 version. Hope this helps. (Adapted from Ciprian Rarau's answer)

@Sunil Targe 这里是 Swift3 版本。希望这可以帮助。(改编自 Ciprian Rarau 的回答)

Convert data to JSON

将数据转换为 JSON

func dataToJSON(data: Data) -> Any? {
   do {
       return try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
   } catch let myJSONError {
       print(myJSONError)
   }
   return nil
}

Convert from JSON to data

从 JSON 转换为数据

func jsonToData(json: Any) -> Data? {
    do {
        return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil;
}

回答by eddieespinal

Swift 4 that works for me:

对我有用的 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;
}

回答by Ekambaram E

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()

    }
}