【问题标题】:Dictionary values getting swapped字典值被交换
【发布时间】:2018-01-14 12:10:00
【问题描述】:

我需要将输入 json 作为 -

[{"QuestionId":77,"OptionId":297}]

但是,当我执行 array.append(dict) 时,我得到的数组是包含相反顺序的键值的字典。

[["OptionId": 297, "QuestionId": 77]]

“OptionId”和“QuestionId”似乎互换了位置。请问,谁能纠正我这个问题。

我还需要在调用 webservice 时传递一个 json 作为输入参数。我用 alamofire 来做。我的 json 输入为 - [{"QuestionId":77,"OptionId":297},{"QuestionId":78,"OptionId":304}] 我怎样才能做到这一点? 我试过了 func callPostAnswersAPI(参数: Array>) {

    var request = URLRequest(url: URL(string: "http://192.168.1.56/OnlineExamPortal/api/Question/PostAnswer")!)        
    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
    let str = String(data: request.httpBody!, encoding: String.Encoding.utf8)      
    Alamofire.request(str!)
        .responseJSON { response in
            switch response.result {
            case .failure(let error):
                print(error)

                if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
                    print(responseString)
                }
            case .success(let responseObject):
                print(responseObject)
            }
    }

}

在 print(str!) 处,我得到了正确格式的 json,但是在将其传递给 alamofire.request 后,它会添加反斜杠。因此,响应进入 .failure 循环。 我是否遵循正确的程序?

【问题讨论】:

  • 字典值没有顺序,没有交换,因为没有顺序。
  • 感谢您的回答。我应该怎么做才能取回相同的订单?
  • 使用不同的数据结构。
  • @Dyana 如果要保持顺序,请使用任何有序集合,例如 Arrays。
  • 我的 json 输入参数是一个字典数组。

标签: ios json swift nsdictionary


【解决方案1】:

JSON 对象在 JSON 规范中定义为无序集合。

对象是一组无序的名称/值对。 (http://json.org/)

如果顺序对您很重要,那么您应该使用不同的集合类型。

【讨论】:

  • 你能举个例子。我不确定需要如何处理。我是 swift 新手。
【解决方案2】:

来自Apple Documentation

每个字典都是键值对的无序集合。

它没有顺序,所以没有交换发生。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2015-10-18
    相关资源
    最近更新 更多