ios 快速将数组转换为 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28325268/
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
Convert array to JSON string in swift
提问by DrPatience
How do you convert an array to a JSONstring in swift?
Basically I have a textfield with a button embedded in it.
When button is pressed, the textfield text is added unto the testArray
.
Furthermore, I want to convert this array to a JSONstring.
如何快速将数组转换为JSON字符串?基本上我有一个文本字段,其中嵌入了一个按钮。当按钮被按下时,文本字段文本被添加到testArray
. 此外,我想将此数组转换为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 JSONstring using my savetoDictionart()
method.
我还想使用我的方法返回JSON字符串savetoDictionart()
。
回答by David Berry
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.
尽管您可能不应该使用强制展开,但它为您提供了正确的起点。
回答by Jon Vogel
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. Here is Apples Documentation, and a quick tutorial for a starting example.
回答by Robert Chen
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. But one potential use-case for JSON stringify is Multipart Post, which AlamoFire nows supports.
有利于传输的 JSON 字符串不会经常出现,因为您可以对 HTTP 主体进行 JSON 编码。但是 JSON stringify 的一个潜在用例是 Multipart Post,AlamoFire 现在支持它。
回答by pawan gupta
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 字符串..
回答by Mitul Marsoniya
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 tempJsonvariable when you want to use.
注意:-当您想使用时使用tempJson变量。
回答by mert
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)
回答by Tung Tran
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
回答by Mr.Javed Multani
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% 工作测试
回答by gnasher729
Hint: To convert an NSArray containing JSON compatible objects to an NSData object containing a JSON document, use the appropriate method of NSJSONSerialization. JSONObjectWithData is not it.
提示:要将包含 JSON 兼容对象的 NSArray 转换为包含 JSON 文档的 NSData 对象,请使用适当的 NSJSONSerialization 方法。JSONObjectWithData 不是。
Hint 2: You rarely want that data as a string; only for debugging purposes.
提示 2:您很少希望将数据作为字符串;仅用于调试目的。
回答by kalpesh
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
}