【问题标题】:fetch json data into swift uitable view将 json 数据获取到 swift uitableview
【发布时间】:2019-02-14 08:05:08
【问题描述】:
Below is my json file 

网址是http://localhost/country.php 我希望这些数据快速进入合适的视图 { 名称:[“印度”,“美国”,“中国”] }

 let url = NSURL(string: "http://localhost/country.php")
let userdata = NSData(contentsOf: url! as URL)
do {
    let values = try JSONSerialization.jsonObject(with: userdata as! Data, options: .allowFragments) as! NSDictionary
    print(values)
    print("Parse success")
} catch let error as NSError
{
    print(error)
    return
}

这是代码 请帮忙

【问题讨论】:

  • 到目前为止,您尝试了什么? SO上有很多关于如何快速解析简单JSON的帖子。顺便提一句。你看过你的网址了吗?
  • 收到错误“错误域 = NSCocoaErrorDomain 代码 = 3840“字符 2 周围的对象中的值没有字符串键。” UserInfo={NSDebugDescription = 字符 2 周围的对象中的值没有字符串键。}”
  • 请向我们展示一些您尝试解析 JSON 的代码以及发生错误的位置(编辑您的问题)
  • 查看已编辑的问题
  • 不要在没有必要的情况下在 Swift 代码中使用 NS* 类型。

标签: json swift uitableview


【解决方案1】:

所以。首先:您的JSON 不是有效的JSON,并且您的网址(当然)不起作用。我猜你的 JSON 是这样的:

{
"name": ["India",
         "USA",
         "China"
        ]
}

如果是这样,您可以像这样更改代码并且它按预期工作:

let jsonString = """
{
"name": ["India",
         "USA",
         "China"
        ]
}
"""

let userData = jsonString.data(using: .utf8)!

do {
    let values = try JSONSerialization.jsonObject(with: userData) as! [String: Any]
    print(values)
    print("Parse success")
} catch let error as NSError
{
    print(error)
}

就像已经提到的一条评论:如果不是真的需要,尽量避免在 Swift 中使用NStypes。

希望对您有所帮助。

此外:从服务器同步加载响应通常是一种不好的做法。您应该使用URLSession 并异步执行。不过这是另一回事了……

因此,您的用例的完整示例如下所示:

let url = URL(string: "http://localhost/country.php")!
let userData = try! Data(contentsOf: url)

do {
    let values = try JSONSerialization.jsonObject(with: userData) as! [String: Any]
    print(values)
    print("Parse success")
} catch let error as NSError
{
    print(error)
}

我在上面的例子中强制展开。我不建议这样做。 Savely 打开你的选项是更好的方法。

【讨论】:

  • ... 如果预期对象是集合类型,指定 .allowFragments 也是不好的做法。省略options 参数。
  • @vadian 谢谢你的提示,这是正确的。我编辑了我的答案。
  • 我想从url解析
  • @JanviRamani 编辑了我的答案。就像提到的那样,我无法使用该 url,因为它被寻址到 localhost...
  • @JanviRamani 如果它有效并且你喜欢我的回答,如果你接受我将不胜感激:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 2016-12-28
  • 1970-01-01
相关资源
最近更新 更多