【问题标题】:How to convert xml and json data in swift 3如何在swift 3中转换xml和json数据
【发布时间】:2017-08-10 09:18:57
【问题描述】:

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

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!)
}

这是来自网络服务的响应:

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

【问题讨论】:

  • 您问题中的回复是纯JSON 回复,XML 部分在哪里?你的问题是什么,好像你已经在解析了?
  • 好的,先生明白了。我想将这些数据存储在不同的数组中。比如 id 在一个数组中,imageName 在另一个数组中
  • 如何从这个响应中检索到数组?
  • 看看我的回答。你没有告诉我存储JSON响应的变量的类型,所以我做了一个假设,告诉我是不是别的东西,我会更新我的答案。
  • jason 响应存储在字符串变量中......变量是 currentElement

标签: json xml swift web-services


【解决方案1】:

借助以下代码块,您可以将任何复杂的 XML 转换为 JSON。我正在转换 50 页的 XML,它就像魅力一样。获得 json 后,您可以直接将其映射到您的模型类。

import Foundation
class ParseXMLData: NSObject, XMLParserDelegate {

var parser: XMLParser
var elementArr = [String]()
var arrayElementArr = [String]()
var str = "{"

init(xml: String) {
    parser = XMLParser(data: xml.replaceAnd().replaceAposWithApos().data(using: String.Encoding.utf8)!)
    super.init()
    parser.delegate = self
}

func parseXML() -> String {
    parser.parse()

    // Do all below steps serially otherwise it may lead to wrong result
    for i in self.elementArr{
        if str.contains("\(i)@},\"\(i)\":"){
            if !self.arrayElementArr.contains(i){
                self.arrayElementArr.append(i)
            }
        }
        str = str.replacingOccurrences(of: "\(i)@},\"\(i)\":", with: "},") //"\(element)@},\"\(element)\":"
    }

    for i in self.arrayElementArr{
        str = str.replacingOccurrences(of: "\"\(i)\":", with: "\"\(i)\":[") //"\"\(arrayElement)\":}"
    }

    for i in self.arrayElementArr{
        str = str.replacingOccurrences(of: "\(i)@}", with: "\(i)@}]") //"\(arrayElement)@}"
    }

    for i in self.elementArr{
        str = str.replacingOccurrences(of: "\(i)@", with: "") //"\(element)@"
    }

    // For most complex xml (You can ommit this step for simple xml data)
    self.str = self.str.removeNewLine()
    self.str = self.str.replacingOccurrences(of: ":[\\s]?\"[\\s]+?\"#", with: ":{", options: .regularExpression, range: nil)

    return self.str.replacingOccurrences(of: "\\", with: "").appending("}")
}

// MARK: XML Parser Delegate
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {

    //print("\n Start elementName: ",elementName)

    if !self.elementArr.contains(elementName){
        self.elementArr.append(elementName)
    }

    if self.str.last == "\""{
        self.str = "\(self.str),"
    }

    if self.str.last == "}"{
        self.str = "\(self.str),"
    }

    self.str = "\(self.str)\"\(elementName)\":{"

    var attributeCount = attributeDict.count
    for (k,v) in attributeDict{
        //print("key: ",k,"value: ",v)
        attributeCount = attributeCount - 1
        let comma = attributeCount > 0 ? "," : ""
        self.str = "\(self.str)\"_\(k)\":\"\(v)\"\(comma)" // add _ for key to differentiate with attribute key type
    }
}

func parser(_ parser: XMLParser, foundCharacters string: String) {
    if self.str.last == "{"{
        self.str.removeLast()
        self.str = "\(self.str)\"\(string)\"#" // insert pattern # to detect found characters added
    }
}

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

    //print("\n End elementName \n",elementName)
    if self.str.last == "#"{ // Detect pattern #
        self.str.removeLast()
    }else{
        self.str = "\(self.str)\(elementName)@}"
    }
}
}

添加字符串扩展

extension String{
    // remove amp; from string
func removeAMPSemicolon() -> String{
    return replacingOccurrences(of: "amp;", with: "")
}

// replace "&" with "And" from string
func replaceAnd() -> String{
    return replacingOccurrences(of: "&", with: "And")
}

// replace "\n" with "" from string
func removeNewLine() -> String{
    return replacingOccurrences(of: "\n", with: "")
}

func replaceAposWithApos() -> String{
    return replacingOccurrences(of: "Andapos;", with: "'")
}
}

从你的班级拨打电话

let xmlStr = "<Your XML string>"
let parser = ParseXMLData(xml: xmlStr)
let jsonStr = parser.parseXML()
print(jsonStr)

希望对你有帮助。

【讨论】:

    【解决方案2】:

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

    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}
    

    要将其放入代码的上下文中:

    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}
    }
    

    【讨论】:

    • 我已经检查过了,但是当我使用它时它会出错 let idArray = jsonResponse.flatMap{$0["Id"]}
    • 我正在使用我的响应而不是此代码作为响应保护 let jsonResponse = (try? JSONSerialization.jsonObject(from: data)) as? [[String:Any]] 否则 {return}
    • 检查我更新的答案。问题是您的JSON 存储在String 中。
    • 很高兴我能帮助@rachnasharma。如果您觉得我的回答有帮助,请考虑接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    相关资源
    最近更新 更多