如何在Swift 3中转换XML和JSON数据 [英] How to convert xml and json data in swift 3

查看:114
本文介绍了如何在Swift 3中转换XML和JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是IOS的新手,我想使用Swift 3将从SOAP Web服务接收的一些混合数据(xml和JSON混合数据)转换为数组. 我在解析器方法的字符串变量中收到此数据.

I am new in IOS and i want convert some mix data(xml and JSON mix data ) receive from SOAP web service into array using swift 3. i receive this data in a string variable in parser method.

func connection(_ connection: NSURLConnection, didFailWithError error: Error){
    print("\(error)")
    print("Some error in your Connection. Please try again.")
    let alert = UIAlertController(title: "Error", message: "No internet connection", preferredStyle: UIAlertControllerStyle.alert)

    // add an action (button)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

    self.present(alert, animated: true, completion: nil)
}

func connectionDidFinishLoading(_ connection: NSURLConnection){

    print("Received \(UInt(webResponseData.count)) Bytes")
    // let theXML = String(webResponseData.mutableBytes, length: webResponseData.length, encoding: String.Encoding.utf8)
    let theXML =  XMLParser(data: webResponseData)
    theXML.delegate = self
    theXML.parse()
    print("\(theXML)")
}

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String, qualifiedName qName: String, attributes attributeDict: [AnyHashable: Any]){
    currentElement = elementName
   // print(currentElement)
}

func parser(_ parser: XMLParser, foundCharacters string: String){

   currentElement = string
    UserDefaults.standard.set(currentElement, forKey: "string")

    //print(currentElement)
   // arr.append(currentElement)
}

func parser(_ parser: XMLParser,didEndElement elementName: String, namespaceURI: String?,qualifiedName qName: String?){

    let sessionelement = UserDefaults.standard.object(forKey: "string")
    print(sessionelement!)
}

这是Web服务的回复:

here is response from from web service:

[{"Id":2,"imgName":"_U11tmp1464839741959976567.jpg","SeqNo":1},
{"Id":1,"imgName":"_U11tmp1464839741959976567.jpg","SeqNo":2},
{"Id":3,"imgName":"_U11tmpIMG-14117-WA59976567.jpg","SeqNo":3}]

推荐答案

这是一个有效的示例,我已经在操场上对其进行了测试.您需要先将JSON String转换为Data对象,然后对其进行解析.

This is a working example, I have tested it in a playground. You need to convert your JSON String to a Data object first, then parse it.

let jsonString = "[{\"Id\":2,\"imgName\":\"_U11tmp1464839741959976567.jpg\",\"SeqNo\":1},{\"Id\":1,\"imgName\":\"_U11tmp1464839741959976567.jpg\",\"SeqNo\":2},{\"Id\":3,\"imgName\":\"_U11tmpIMG-14117-WA59976567.jpg\",\"SeqNo\":3}]"
guard let jsonData = jsonString.data(using: .utf8) else {return}
guard let jsonResponse = (try? JSONSerialization.jsonObject(with: jsonData)) as? [[String:Any]] else {return}
let idArray = jsonResponse.flatMap{$0["Id"] as? Int}
let imageNames = jsonResponse.flatMap{$0["imgName"] as? String}

要将其置于您的代码上下文中:

To put this into context of your code:

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String, qualifiedName qName: String, attributes attributeDict: [AnyHashable: Any]){
    currentElement = elementName
    guard let jsonData = currentElement.data(using: .utf8) else {return}
    guard let jsonResponse = (try? JSONSerialization.jsonObject(with: jsonData)) as? [[String:Any]] else {return}
    let idArray = jsonResponse.flatMap{$0["Id"] as? Int}
    let imageNames = jsonResponse.flatMap{$0["imgName"] as? String}
}

这篇关于如何在Swift 3中转换XML和JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆