gpt4 book ai didi

json - 如何在swift 3中转换xml和json数据

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:35 25 4
gpt4 key购买 nike

我是 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}]

最佳答案

借助以下代码块,您可以将任何复杂的 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: "'")
}
}

从类(class)打电话

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

希望对您有所帮助。

关于json - 如何在swift 3中转换xml和json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45609447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com