gpt4 book ai didi

json - 快速将简单字符串转换为 JSON 字符串

转载 作者:IT王子 更新时间:2023-10-29 05:33:50 26 4
gpt4 key购买 nike

我知道有一个相同标题的问题here .但是在那个问题中,他正在尝试将字典转换为 JSON。但是我有一个像这样的简单刺痛:“花园”

而且我必须将其作为 JSON 发送。我试过 SwiftyJSON 但我仍然无法将其转换为 JSON。

这是我的代码:

func jsonStringFromString(str:NSString)->NSString{

let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
let json = JSON(data: strData!)
let jsonString = json.string

return jsonString!
}

我的代码在最后一行崩溃了:

fatal error: unexpectedly found nil while unwrapping an Optional value

我做错了什么吗?

最佳答案

JSON has to be an array or a dictionary ,它不能只是一个字符串。

我建议您创建一个包含字符串的数组:

let array = ["garden"]

然后从这个数组创建一个 JSON 对象:

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) {
// here `json` is your JSON data
}

如果你需要这个 JSON 作为字符串而不是数据,你可以使用这个:

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) {
// here `json` is your JSON data, an array containing the String
// if you need a JSON string instead of data, then do this:
if let content = String(data: json, encoding: NSUTF8StringEncoding) {
// here `content` is the JSON data decoded as a String
print(content)
}
}

打印:

["garden"]

如果您更喜欢字典而不是数组,请遵循相同的想法:创建字典然后转换它。

let dict = ["location": "garden"]

if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []) {
if let content = String(data: json, encoding: NSUTF8StringEncoding) {
// here `content` is the JSON dictionary containing the String
print(content)
}
}

打印:

{"location":"garden"}

关于json - 快速将简单字符串转换为 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36494529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com