简体   繁体   English

快速将数组转换为 JSON 字符串

[英]Convert array to JSON string in swift

How do you convert an array to a JSON string in swift?如何快速将数组转换为JSON字符串? Basically I have a textfield with a button embedded in it.基本上我有一个文本字段,其中嵌入了一个按钮。 When button is pressed, the textfield text is added unto the testArray .当按钮被按下时,文本字段文本被添加到testArray Furthermore, I want to convert this array to a JSON string.此外,我想将此数组转换为JSON字符串。

This is what I have tried:这是我尝试过的:

func addButtonPressed() {
    if goalsTextField.text == "" {
        // Do nothing
    } else {
        testArray.append(goalsTextField.text)
        goalsTableView.reloadData()
        saveDatatoDictionary()
    }
}

func saveDatatoDictionary() {
    data = NSKeyedArchiver.archivedDataWithRootObject(testArray)
    newData = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(), error: nil) as? NSData
    string = NSString(data: newData!, encoding: NSUTF8StringEncoding) 
    println(string)
}

I would also like to return the JSON string using my savetoDictionart() method.我还想使用我的savetoDictionart()方法返回JSON字符串。

As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.就目前而言,您正在将其转换为数据,然后尝试将数据转换为对象作为 JSON(失败,它不是 JSON)并将其转换为字符串,基本上您有一堆无意义的转换。

As long as the array contains only JSON encodable values (string, number, dictionary, array, nil) you can just use NSJSONSerialization to do it.只要数组只包含 JSON 可编码值(字符串、数字、字典、数组、nil),您就可以使用 NSJSONSerialization 来做到这一点。

Instead just do the array->data->string parts:相反,只需执行 array->data->string 部分:

Swift 3/4斯威夫特 3/4

let array = [ "one", "two" ]

func json(from object:Any) -> String? {
    guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
        return nil
    }
    return String(data: data, encoding: String.Encoding.utf8)
}

print("\(json(from:array as Any))")

Original Answer原答案

let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)

although you should probably not use forced unwrapping, it gives you the right starting point.尽管您可能不应该使用强制展开,但它为您提供了正确的起点。

Swift 3.0 - 4.0 version斯威夫特 3.0 - 4.0 版本

do {

    //Convert to Data
    let jsonData = try JSONSerialization.data(withJSONObject: dictionaryOrArray, options: JSONSerialization.WritingOptions.prettyPrinted)

    //Convert back to string. Usually only do this for debugging
    if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
       print(JSONString)
    }

    //In production, you usually want to try and cast as the root data structure. Here we are casting as a dictionary. If the root object is an array cast as [Any].
    var json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]


} catch {
    print(error.description)
}

The JSONSerialization.WritingOptions.prettyPrinted option gives it to the eventual consumer in an easier to read format if they were to print it out in the debugger. JSONSerialization.WritingOptions.prettyPrinted选项将它以更易于阅读的格式提供给最终消费者,如果他们在调试器中打印出来的话。

Reference: Apple Documentation参考: Apple 文档

The JSONSerialization.ReadingOptions.mutableContainers option lets you mutate the returned array's and/or dictionaries. JSONSerialization.ReadingOptions.mutableContainers选项允许您改变返回的数组和/或字典。

Reference for all ReadingOptions: Apple Documentation所有 ReadingOptions 的参考: Apple 文档

NOTE: Swift 4 has the ability to encode and decode your objects using a new protocol.注意:Swift 4 能够使用新协议对您的对象进行编码和解码。 Here is Apples Documentation , and a quick tutorial for a starting example .这是Apples 文档,以及入门示例快速教程

If you're already using SwiftyJSON:如果您已经在使用 SwiftyJSON:

https://github.com/SwiftyJSON/SwiftyJSON https://github.com/SwiftyJSON/SwiftyJSON

You can do this:你可以这样做:

// this works with dictionaries too
let paramsDictionary = [
    "title": "foo",
    "description": "bar"
]
let paramsArray = [ "one", "two" ]
let paramsJSON = JSON(paramsArray)
let paramsString = paramsJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)

SWIFT 3 UPDATE SWIFT 3 更新

 let paramsJSON = JSON(paramsArray)
 let paramsString = paramsJSON.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions.prettyPrinted)!

JSON strings, which are good for transport, don't come up often because you can JSON encode an HTTP body.有利于传输的 JSON 字符串不会经常出现,因为您可以对 HTTP 主体进行 JSON 编码。 But one potential use-case for JSON stringify is Multipart Post, which AlamoFire nows supports.但是 JSON stringify 的一个潜在用例是 Multipart Post,AlamoFire 现在支持它。

How to convert array to json String in swift 2.3如何在swift 2.3中将数组转换为json字符串

var yourString : String = ""
do
{
    if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(yourArray, options: NSJSONWritingOptions.PrettyPrinted)
    {
        yourString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
    }
}
catch
{
    print(error)
}

And now you can use yourSting as JSON string..现在您可以使用 yourSting 作为 JSON 字符串..

SWIFT 2.0斯威夫特 2.0

var tempJson : NSString = ""
do {
    let arrJson = try NSJSONSerialization.dataWithJSONObject(arrInvitationList, options: NSJSONWritingOptions.PrettyPrinted)
    let string = NSString(data: arrJson, encoding: NSUTF8StringEncoding)
    tempJson = string! as NSString
}catch let error as NSError{
    print(error.description)
}

NOTE:- use tempJson variable when you want to use.注意:-当您想使用时使用tempJson变量。

Swift 5斯威夫特 5

This generic extension will convert an array of objects to a JSON string from which it can either be:这个通用extension将一个对象array转换为一个 JSON string ,它可以是:

  • saved to the App's Documents Directory (iOS/MacOS)保存到应用程序的文档目录 (iOS/MacOS)
  • output directly to a file on the Desktop (MacOS)直接输出到桌面上的文件 (MacOS)

. .

extension JSONEncoder {
    static func encode<T: Encodable>(from data: T) {
        do {
            let jsonEncoder = JSONEncoder()
            jsonEncoder.outputFormatting = .prettyPrinted
            let json = try jsonEncoder.encode(data)
            let jsonString = String(data: json, encoding: .utf8)
            
            // iOS/Mac: Save to the App's documents directory
            saveToDocumentDirectory(jsonString)
            
            // Mac: Output to file on the user's Desktop
            saveToDesktop(jsonString)
            
        } catch {
            print(error.localizedDescription)
        }
    }
    
    static private func saveToDocumentDirectory(_ jsonString: String?) {
        guard let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
        let fileURL = path.appendingPathComponent("Output.json")
        
        do {
            try jsonString?.write(to: fileURL, atomically: true, encoding: .utf8)
        } catch {
            print(error.localizedDescription)
        }
        
    }
    
    static private func saveToDesktop(_ jsonString: String?) {
        let homeURL = FileManager.default.homeDirectoryForCurrentUser
        let desktopURL = homeURL.appendingPathComponent("Desktop")
        let fileURL = desktopURL.appendingPathComponent("Output.json")
        
        do {
            try jsonString?.write(to: fileURL, atomically: true, encoding: .utf8)
        } catch {
            print(error.localizedDescription)
        }
    }
}

Example:例子:

struct Person: Codable {
    var name: String
    var pets: [Pet]
}

struct Pet: Codable {
    var type: String
}

extension Person {
    static func sampleData() -> [Person] {
        [
            Person(name: "Adam", pets: []),
            Person(name: "Jane", pets: [
                    Pet(type: "Cat")
            ]),
            Person(name: "Robert", pets: [
                    Pet(type: "Cat"),
                    Pet(type: "Rabbit")
            ])
        ]
    }
}

Usage:用法:

JSONEncoder.encode(from: Person.sampleData())

Output:输出:

This will create the following correctly formatted Output.json file:这将创建以下格式正确的Output.json文件:

[
  {
    "name" : "Adam",
    "pets" : [

    ]
  },
  {
    "name" : "Jane",
    "pets" : [
      {
        "type" : "Cat"
      }
    ]
  },
  {
    "name" : "Robert",
    "pets" : [
      {
        "type" : "Cat"
      },
      {
        "type" : "Rabbit"
      }
    ]
  }
]
extension Array where Element: Encodable {
    func asArrayDictionary() throws -> [[String: Any]] {
        var data: [[String: Any]] = []

        for element in self {
            data.append(try element.asDictionary())
        }
        return data
    }
}

extension Encodable {
        func asDictionary() throws -> [String: Any] {
            let data = try JSONEncoder().encode(self)
            guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
                throw NSError()
            }
            return dictionary
        }
}

If you're using Codable protocols in your models these extensions might be helpful for getting dictionary representation ( Swift 4 )如果您在模型中使用 Codable 协议,这些扩展可能有助于获得字典表示( Swift 4

For Swift 4.2, that code still works fine对于 Swift 4.2,该代码仍然可以正常工作

 var mnemonic: [String] =  ["abandon",   "amount",   "liar", "buyer"]
    var myJsonString = ""
    do {
        let data =  try JSONSerialization.data(withJSONObject:mnemonic, options: .prettyPrinted)
       myJsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
    } catch {
        print(error.localizedDescription)
    }
    return myJsonString

Hint: To convert an NSArray containing JSON compatible objects to an NSData object containing a JSON document, use the appropriate method of NSJSONSerialization.提示:要将包含 JSON 兼容对象的 NSArray 转换为包含 JSON 文档的 NSData 对象,请使用适当的 NSJSONSerialization 方法。 JSONObjectWithData is not it. JSONObjectWithData 不是。

Hint 2: You rarely want that data as a string;提示 2:您很少希望将数据作为字符串; only for debugging purposes.仅用于调试目的。

For Swift 3.0 you have to use this:对于 Swift 3.0,你必须使用这个:

var postString = ""
    do {
        let data =  try JSONSerialization.data(withJSONObject: self.arrayNParcel, options: .prettyPrinted)
        let string1:String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String

        postString = "arrayData=\(string1)&user_id=\(userId)&markupSrcReport=\(markup)"
    } catch {
        print(error.localizedDescription)
    }
    request.httpBody = postString.data(using: .utf8)

100% working TESTED 100% 工作测试

Swift 5斯威夫特 5

Make sure your object confirm Codable .确保您的对象确认Codable

Swift's default variable types like Int, String, Double and ..., all are Codable that means we can convert theme to Data and vice versa. Swift 的默认变量类型,如 Int、String、Double 和 ...,都是Codable ,这意味着我们可以将主题转换为数据,反之亦然。

For example, let's convert array of Int to String Base64例如,让我们将 Int 数组转换为 String Base64

let array = [1, 2, 3]
let data = try? JSONEncoder().encode(array)
nsManagedObject.array = data?.base64EncodedString()

Make sure your NSManaged variable type is String in core data schema editor and custom class if your using custom class for core data objects.如果您对核心数据对象使用自定义类,请确保您的NSManaged变量类型在核心数据模式编辑器和自定义类中为String

let's convert back base64 string to array:让我们将 base64 字符串转换回数组:

var getArray: [Int] {
    guard let array = array else { return [] }
    guard let data = Data(base64Encoded: array) else { return [] }
    guard let val = try? JSONDecoder().decode([Int].self, from: data) else { return [] }
    return val
}

Do not convert your own object to Base64 and store as String in CoreData and vice versa because we have something that named Relation in CoreData (databases).不要将您自己的对象转换为Base64并在 CoreData 中存储为 String,反之亦然,因为我们在 CoreData(数据库)中有名为Relation东西。

You can try this.你可以试试这个。

func convertToJSONString(value: AnyObject) -> String? {
        if JSONSerialization.isValidJSONObject(value) {
            do{
                let data = try JSONSerialization.data(withJSONObject: value, options: [])
                if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
                    return string as String
                }
            }catch{
            }
        }
        return nil
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM