【问题标题】:Using loops to store multiple json object into arrays使用循环将多个 json 对象存储到数组中
【发布时间】:2017-02-02 15:13:58
【问题描述】:

我已经做了一个 web 服务来检索数据的 JSON,如下所示:

(这是存储在变量数据中)

{"0":{"categoryId":"1","category":"Restaurants"},"1":{"categoryId":"2","category":"Attractions"},"type":"1006","status":"OK"}

但是我无法成功检索每个对象,因为我想将它们动态存储到数组中,例如

var categoryIDArray = ["1", "2"];
var categoryArray   = ["Restaurants", "Attractions"];

因此,我最初想执行以下逻辑,因为我在 android studio for java 和 cordova for javascript 中做了类似的事情

//try 
//{
//    for(var i = 0; i < data.count(); i++)
//    {
//        categoryIDArray[i] = data[i].categoryId;
//        categoryArray[i]   = data[i].category;
//    }
//}
//catch(Exception ex)
//{
//    //Catch null pointer or wrong format for json
//}

但是我已经被困在 swift 2 中检索 JSON 的数量了。

//I tried doing the following to see if I am able to retrieve data 0 JSON but it failed
//print(data![0]);

以下代码有效,但只能提取单个数据

do{
    let json: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
    let test1 = (json!["status"] as? String)!
    let test2 = (json!["0"] as? String)!

    print(test1) //shows "OK" 
    print(test2) //shows nil instead of {"categoryId":"1","category":"Restaurants"}

} catch {
    print("JSON parse error")
}

有什么建议吗?谢谢!

【问题讨论】:

  • 为什么 web 服务会创建一个以整数为键的字典而不是数组?这不是好的 JSON 格式...
  • @EricAya 嗨,可以就一个好的 json 格式提出建议吗?我现在可以进行更改
  • 我会为字典使用一个数组,类似于:{"type": "1006", "status": "OK", "data": [{"categoryId": "1", "category": "Restaurants"}, {"categoryId": "2", "category": "Attractions"}]}
  • 然后您将 json["data"] 的结果转换为字典数组:[[String: Any]] 并能够循环。
  • @EricAya:这实际上不是一种合法的格式。 JSON 中的字典键必须是字符串。

标签: arrays json swift2


【解决方案1】:

让我们检查一下这个语句:

let test1 = (json!["status"] as? Int)!

json!意思是:取对象json,解包,如果为nil就崩溃。

json!["status"] 意思是:尝试使用"status"作为对象json中的索引。如果 json 不是字典,这将崩溃。

json!["status"] 为? Int 表示:获取 json!["status"] 的结果并尝试将其转换为 Int,如果失败则产生 nil。

(json!["status"] as? Int)!意思是:从上一行中取出可选的 int,解包,如果为 nil 则崩溃。

在一行代码中大约有四个可能的崩溃。

【讨论】:

    【解决方案2】:

    请试试这个。我确定它正在工作

    var arrCatNumber : [String]? = []
    var arrCatName : [String]? = []
    let data = ["0":["categoryId":"1","category":"Restaurants"],"1":["categoryId":"2","category":"Attractions"],"type":"1006","status":"OK"]
    //here data is assumed your json data
    
    
    for index in 0...data.count - 3{ 
     //data.count = 4 means 5 times lopping and we need actually first for 2 than we minus 3.
     //If data["2"],data["3"] come in response than work fine no need any extra implementation  
    
        let strIndex = String(index)
    
        if let test1 = data[strIndex] as? [String : String]{
            arrCatNumber?.append(test1["categoryId"]!)
            arrCatName?.append(test1["category"]!)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-21
      • 2019-08-26
      • 1970-01-01
      • 2019-10-02
      • 2017-01-15
      • 1970-01-01
      • 2014-06-26
      • 2018-07-07
      相关资源
      最近更新 更多