快速将简单字符串转换为 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36494529/
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 a simple string to JSON String in swift
提问by iBug
I know there is a question with same title here. But in that question, he is trying to convert a dictionary into JSON. But I have a simple sting like this: "garden"
我知道有一个与同名的一个问题在这里。但在那个问题中,他试图将字典转换为 JSON。但我有一个像这样的简单刺痛:“花园”
And I have to send it as JSON. I have tried SwiftyJSON but still I am unable to convert this into JSON.
我必须将它作为 JSON 发送。我已经尝试过 SwiftyJSON,但仍然无法将其转换为 JSON。
Here is my code:
这是我的代码:
func jsonStringFromString(str:NSString)->NSString{
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
let json = JSON(data: strData!)
let jsonString = json.string
return jsonString!
}
My code crashes at the last line:
我的代码在最后一行崩溃:
fatal error: unexpectedly found nil while unwrapping an Optional value
Am I doing something wrong?
难道我做错了什么?
回答by Eric Aya
JSON has to be an array or a dictionary, it can't be only a String.
JSON 必须是一个数组或一个字典,它不能只是一个字符串。
I suggest you create an array with your String in it:
我建议你用你的字符串创建一个数组:
let array = ["garden"]
Then you create a JSON object from this array:
然后从这个数组创建一个 JSON 对象:
if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) {
// here `json` is your JSON data
}
If you need this JSON as a String instead of data you can use this:
如果您需要将此 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)
}
}
Prints:
印刷:
["garden"]
[“花园”]
If you prefer having a dictionary rather than an array, follow the same idea: create the dictionary then convert it.
如果您更喜欢使用字典而不是数组,请遵循相同的想法:创建字典然后转换它。
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)
}
}
Prints:
印刷:
{"location":"garden"}
{“位置”:“花园”}
回答by mding5692
Swift 3 Version:
斯威夫特 3 版本:
let location = ["location"]
if let json = try? JSONSerialization.data(withJSONObject: location, options: []) {
if let content = String(data: json, encoding: .utf8) {
print(content)
}
}

