我有一个名为points.json的JSON文件,以及一个读取函数,如:
private func readJson() {
let file = Bundle.main.path(forResource: "points", ofType: "json")
let data = try? Data(contentsOf: URL(fileURLWithPath: file!))
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
print(jsonData)
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,有什么帮助吗?
我尝试将JSON字符串转换为JSON对象,但JSONSerialization输出后是nilJSON.
响应字符串:
[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]
Run Code Online (Sandbox Code Playgroud)
我尝试使用下面的代码转换此字符串:
let jsonString = response.result.value
let data: Data? = jsonString?.data(using: .utf8)
let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:AnyObject]
print(json ?? "Empty Data")
Run Code Online (Sandbox Code Playgroud) 作为一个编码练习,我写了一个小程序,将Web上的MySql数据带到iPhone上.在服务器端.我编写了php脚本来获取脚本以返回json数据.
在xcode上我有
[code]
.
.
.
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: [])
print(jsonString!)
.
.
.
[/code]
Run Code Online (Sandbox Code Playgroud)
在xcode控制台中,我有这个:
[code]
(
{
Address = "1 Infinite Loop Cupertino, CA";
Latitude = "37.331741";
Longitude = "-122";
Name = Apple;
}
)
[/code]
I have a function
[code]
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil …Run Code Online (Sandbox Code Playgroud) 我将此 JSON 保存在文件(“list_catalog.json”)中:
[
{
"idcatalog": 1,
"imgbase64": "",
"urlImg": "http://172.../page01.jpg",
"urlPages": "http://172.../catalog_1_pages.json",
"dt_from": "",
"dt_to": ""
},
{
"idcatalog": 2,
"imgbase64": "",
"urlImg": "http://172.../1.jpg",
"urlPages": "http://172.../2_pages.json",
"category": [
{
"id": 1,
"lib": "lib"
}
],
"dt_to": ""
}
]
Run Code Online (Sandbox Code Playgroud)
我可以通过以下方式获取该文件:
if let url = URL(string: "http://172.../list_catalogs.json") {
do {
let contents = try String(contentsOf: url)
print(contents)
} catch {
// contents could not be loaded
}
}
Run Code Online (Sandbox Code Playgroud)
但我无法在字典中转换这个字符串。为了将数据转换为字符串,我使用这个函数:
func convertToDictionary(text: String) -> [String: Any]? {
if let data = …Run Code Online (Sandbox Code Playgroud)