如何在swift 3中转换xml和json数据
我是IOS新手,我希望使用swift 3将从SOAP web服务接收的一些混合数据(xml和JSON混合数据)转换为数组。 我在解析器方法中以字符串变量的形式接收这些数据如何在swift 3中转换xml和json数据,json,xml,swift,web-services,Json,Xml,Swift,Web Services,我是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.")
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服务的响应:
[{"Id":2,"imgName":"_U11tmp1464839741959976567.jpg","SeqNo":1},
{"Id":1,"imgName":"_U11tmp1464839741959976567.jpg","SeqNo":2},
{"Id":3,"imgName":"_U11tmpIMG-14117-WA59976567.jpg","SeqNo":3}]
这是一个有效的例子,我已经在一个操场上进行了测试。您需要首先将JSON
字符串
转换为数据
对象,然后解析它
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}
}
借助下面的代码块,您可以将任何复杂的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)
let xmlStr=“”
让parser=ParseXMLData(xml:xmlStr)
让jsonStr=parser.parseXML()
打印(jsonStr)
我希望这能对您有所帮助。您问题中的回答是一个纯
JSON
回答,XML
部分在哪里?你的问题是什么,看起来你已经在做解析了?好的,先生,明白了。我想把这些数据存储在不同的数组中。比如一个数组中的id和另一个数组中的imageName如何从这个数组的响应中检索?查看我的答案。您没有告诉我存储JSON
响应的变量的类型,所以我做了一个假设,告诉我它是否是其他的,我将更新我的答案。jason响应存储在字符串变量中…变量是CurrentElement我已经检查过它,但是当我使用let-idArray=jsonResponse.flatMap{$0[“Id”]}我使用的是我的响应,而不是响应保护的这段代码,让jsonResponse=(try?JSONSerialization.jsonObject(from:data))作为?[[String:Any]]其他{return}检查我的更新答案。问题是你的<代码> JSON<代码>被存储在<代码>字符串< /代码>中。很高兴我能帮助@ RhannasHARMA。如果你发现我的答案有用,请考虑接受它。