简体   繁体   English

如何使用 SwiftyJSON 将字符串转换为 JSON

[英]How to convert a string into JSON using SwiftyJSON

The string to convert:要转换的字符串:

[{"description": "Hi","id":2,"img":"hi.png"},{"description": "pet","id":10,"img":"pet.png"},{"description": "Hello! :D","id":12,"img":"hello.png"}]

The code to convert the string:转换字符串的代码:

var json = JSON(stringLiteral: stringJSON)

The string is converted to JSON and when I try to count how many blocks are inside this JSON (expected answer = 3), I get 0.该字符串被转换为 JSON,当我尝试计算这个 JSON 中有多少块时(预期答案 = 3),我得到 0。

print(json.count)

Console Output: 0控制台输出: 0

What am I missing?我错过了什么? Help is very appreciated.非常感谢帮助。

Actually, there was a built-in function in SwifyJSON called parse实际上,SwifyJSON 中有一个内置函数叫做parse

/**
 Create a JSON from JSON string
- parameter string: Normal json string like '{"a":"b"}'

- returns: The created JSON
*/
public static func parse(string:String) -> JSON {
    return string.dataUsingEncoding(NSUTF8StringEncoding)
        .flatMap({JSON(data: $0)}) ?? JSON(NSNull())
}

Note that请注意

var json = JSON.parse(stringJSON)

its now changed to它现在改为

var json = JSON.init(parseJSON:stringJSON)

I fix it on this way.我是这样修的。

I will use the variable "string" as the variable what contains the JSON.我将使用变量“string”作为包含 JSON 的变量。

1. 1.

encode the sting with NSData like this像这样用 NSData 编码刺痛

var encodedString : NSData = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
  1. un-encode the string encoded (this may be sound a little bit weird hehehe):取消编码的字符串编码(这可能听起来有点奇怪呵呵):

    var finalJSON = JSON(data: encodedString) var finalJSON = JSON(数据:编码字符串)

Then you can do whatever you like with this JSON.然后你可以用这个 JSON 做任何你喜欢的事情。

Like get the number of sections in it (this was the real question) with就像获取其中的部分数量(这是真正的问题)

finalJSON.count or print(finalJSON[0]) or whatever you like to do. finalJSON.countprint(finalJSON[0])或任何您喜欢做的事情。

I'm using as follows:我使用如下:

let yourString = NSMutableString()

let dataToConvert = yourString.data(using: String.Encoding.utf8.rawValue)

let json = JSON(data: dataToConvert!)

print("\nYour string: " + String(describing: json))

斯威夫特4

let json = string.data(using: String.Encoding.utf8).flatMap({try? JSON(data: $0)}) ?? JSON(NSNull())

There is a built-in parser in SwiftyJSON: SwiftyJSON 中有一个内置的解析器:

let json = JSON.init(parseJSON: responseString)

Don't forget to import SwiftyJSON!不要忘记导入 SwiftyJSON!

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

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