在 Swift/Xcode 中将 JSON 从 AlamoFire/SwiftyJSON 转换为字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28862087/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:45:53  来源:igfitidea点击:

Converting JSON from AlamoFire/SwiftyJSON to Dictionary in Swift/Xcode

xcodeswiftalamofireswifty-json

提问by davidbii

My head is going to explode :) - I've been trying to get a JSON String from my server to a Dictionary Value, and I can't get it to work.

我的头要爆炸了:) - 我一直试图从我的服务器获取一个 JSON 字符串到一个字典值,但我无法让它工作。

I'm trying to get (from my Server - this is dynamic and I want my app to be able to pull new data from the server when needed):

我正在尝试获取(从我的服务器 - 这是动态的,我希望我的应用程序能够在需要时从服务器获取新数据):

{"1":"Location 1","2":"Location 2","3":"Location 3"}

To this Dictionary in Xcode using Swift:

使用 Swift 在 Xcode 中的这个字典:

  var labels = [

        1 : "Location 1",
        2 : "Location 2",
        3 : "Location 3"

    ]

This has got to be pretty straight forward, but for the life of me I can't figure it out...

这必须非常简单,但对于我的生活,我无法弄清楚......

Here's my Swift - I can get it to pull the information from the server, but I can't get it into a dictionary like I need

这是我的 Swift - 我可以让它从服务器中提取信息,但我无法将其放入我需要的字典中

var postEndpoint: String = "http://www.myserver.net/app/campus.php"

    Alamofire.request(.GET, postEndpoint)
        .responseJSON { (request, response, data, error) in
            if let anError = error
            {
                println("error")
                println(error)
            }
            else if let data: AnyObject = data 
            {
                 let post = JSON(data)
                 println(post)
            }
    }

which results in:

这导致:

{
  "1" : "Location 1",
  "2" : "Location 2",
  "3" : "Location 3"
}

The End Result that I'm using this for is an iBeacon implementation with the following code:

我使用它的最终结果是具有以下代码的 iBeacon 实现:

 let knownBeacons = beacons.filter{ 
let locationID = post[String(closestBeacon.minor.integerValue)]!
.proximity != CLProximity.Unknown } if (knownBeacons.count > 0) { let closestBeacon = knownBeacons[0] as CLBeacon let locationID = post[closestBeacon.minor.integerValue] self.locationLabel.text = locationID self.view.backgroundColor = self.colors[closestBeacon.minor.integerValue] }

The error I'm getting is at self.locationLabel.text = locationID 'JSON' is not convertible to 'String', I do not get this error when I use the static var labels dictionary. Am I trying to get the data from the server incorrectly? What am I doing wrong??? I think the var labels having an undeclared Type allows Swift to figure out what it needs to, how do I do the same from the JSON part?

我得到的错误是 self.locationLabel.text = locationID 'JSON' is not convertible to 'String',当我使用静态 var 标签字典时,我没有收到这个错误。我是否试图错误地从服务器获取数据?我究竟做错了什么???我认为具有未声明类型的 var 标签允许 Swift 弄清楚它需要什么,我如何从 JSON 部分做同样的事情?

回答by cnoon

Oh you were so close!

哦,你是如此接近!

Your problem is that your postdictionary is a [String: String]and not an [Int: String]like you think it is. You have a few ways to fix it, but the easiest for now would be to just do the following:

你的问题是你的post字典[String: String]不是[Int: String]你想的那样。您有几种方法可以修复它,但目前最简单的方法是执行以下操作:

let json = JSON(data)
var post = [Int: String]()

for (key, object) in json {
    post[key.toInt()!] = object.stringValue
}

While this will certainly work, a better solution would be to convert your postinto a [Int: String]typed dictionary like you expect in the responseJSONclosure. Here's how this could work.

虽然这肯定会奏效,但更好的解决方案是将您post[Int: String]字典转换为您在responseJSON闭包中期望的类型字典。这是如何工作的。

let responseString = "{\"1\":\"Location 1\",\"2\":\"Location 2\",\"3\":\"Location 3\"}"

if let dataFromString = responseString.data(using: String.Encoding.utf8, allowLossyConversion: false) {

    let json = JSON(data: dataFromString)

    var labels = json.dictionaryObject! as! [String: String]

    print(labels)
}

You would want to add some safety around what to do if the keyor objectwere not able to be converted to an Intor Stringrespectively, but I'll leave that to you.

如果keyobject无法分别转换为 anIntString,您可能希望为该做什么添加一些安全性,但我将把它留给您。

回答by Ali Momen Sani

If having a [String: String]is sufficient for anyone, he/she could try the following code:

如果有一个[String: String]对任何人来说都足够了,他/她可以尝试以下代码:

closestBeacon.minor.integerValue

The result is: ["2": "Location 2", "1": "Location 1", "3": "Location 3"].

结果是: ["2": "Location 2", "1": "Location 1", "3": "Location 3"]

回答by davidbii

I solved this by working in reverse. I changed the call. Instead of getting the Dictionary of Values from the Server, I just query the Server with the Single Variable that I already had from the variable

我通过反向工作解决了这个问题。我换了电话。我没有从服务器获取值字典,而是使用我已经从变量中获得的单个变量来查询服务器

##代码##

And then get the string that I needed from the server and that solved my problem. Still has the same number of calls to the server, so no additional overhead was added. Sometimes you just have to think outside the box that you put yourself into.

然后从服务器获取我需要的字符串并解决了我的问题。对服务器的调用次数仍然相同,因此没有增加额外的开销。有时,您只需要跳出自己的框框思考即可。

If anybody can solve this the other direction, I'm still eager to hear how it could work.

如果有人可以从另一个方向解决这个问题,我仍然很想知道它是如何工作的。