如何解析 JSON,它在 json 对象中包含一个数组,但没有 arrayName

How do I parse a JSON which contains an array inside a json Object without a arrayName

我得到一个这样的 JSON 数组

[
{
"accNo":"8567856",
"ifscCode":"YESB000001"
},
{
"accNo":"85678556786",
"ifscCode":"YESB000001"
}
]

我在 json 中得到一个没有 arrayName 的数组。 我试图在 swift 3 中解析此 JSON 并对其进行类型转换以获取所有数组中的值(使用 as?NSArray、NSDictionary、[Array -String、AnyObject-] 等)。但它都失败了。 swift 中有没有办法获取数组值

您可能想查看 SwiftyJSON 但这是您使用 Foundation 的答案。

Swift 4:

let str = """
[
{
"accNo":"8567856",
"ifscCode":"YESB000001"
},
{
"accNo":"85678556786",
"ifscCode":"YESB000001"
}
]
"""

let data = str.data(using: .utf8)!

do {

    let json = try JSONSerialization.jsonObject(with: data) as? [[String:String]]

    for item in json! {

        if let accNo = item["accNo"] {
            print(accNo)
        }

        if let ifscCode = item["ifscCode"] {
            print(ifscCode)
        }
    }

} catch {
    print("Error deserializing JSON: \(error)")
}

使用JSONSerialization将数据转换为字符串字典数组,[[String:String]]

let str = """
[
{
"accNo":"8567856",
"ifscCode":"YESB000001"
},
{
"accNo":"85678556786",
"ifscCode":"YESB000001"
}
]
"""
let data = str.data(using: .utf8)!
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [[String:String]]
print(json) // [["accNo": "8567856", "ifscCode": "YESB000001"], ["accNo": "85678556786", "ifscCode": "YESB000001"]]