代码之家  ›  专栏  ›  技术社区  ›  Jeesson_7

我如何解析一个JSON,它在一个JSON对象中包含一个数组,而没有arrayName[closed]

  •  2
  • Jeesson_7  · 技术社区  · 8 年前

    我得到了这样的JSON数组

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

    我得到了一个json中没有arrayName的数组。 我试图在swift 3中解析这个JSON,并将其类型转换为所有数组中的值(使用as?NSArray、NSDictionary、[array-String、AnyObject-]等)。但这一切都失败了。swift中有没有获取数组值的方法

    2 回复  |  直到 8 年前
        1
  •  4
  •   Anushk    8 年前

    你可能需要检查一下 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)")
    }
    
        2
  •  1
  •   Puneet Sharma    8 年前

    使用 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"]]