欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swift JSON和XML解析器

程序员文章站 2022-06-16 12:38:49
...

swift Json/XML下载地址

在和服务器交互过程中,字典或者数组和JSON串的转换,具体互换如下:

NSData Json 转化为字典

func decodeToJsonDictFromJsonData(jsonData: NSData) -> NSDictionary {
       
        let dict = try? JSONSerialization.jsonObject(with: jsonData as Data, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
        
    }

json字符串转化为字典

func decodeToJsonDictFromJsonString(jsonString: String) -> NSDictionary {
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        let dict = try? JSONSerialization.jsonObject(with: jsonData as Data, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    
    }

字典转化为字符串

func encodeToJsonStringFromJsonDict(JsonDict:NSDictionary) -> NSString{
        var jsonString:NSString = ""
        
        if JSONSerialization .isValidJSONObject(JsonDict){
            
            let data : NSData! = try? JSONSerialization.data(withJSONObject:JsonDict, options: []) as NSData
            jsonString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue)!
            return jsonString
            
        }
        return jsonString
    }

xml数据转化为字典,本文是本地的一份xml文件

import UIKit

//用户对象
struct User {
    var id: String?  //编号
    var name: String? //姓名
   
}


class ZMMXMLParserKit: NSObject,
                       ZMMXMLParserProtocol,
                       XMLParserDelegate{
    //保存最终解析的结果
    var users:[User] = []
    //当前元素名
    var currentElement = ""
    //当前用户
    var user:User!
    
    func parsingToDictFromFile(filePath: NSString) -> NSDictionary
    {
        let url = NSURL(fileURLWithPath: filePath as String)
        let parser = XMLParser(contentsOf: url as URL)
        parser?.delegate = self
        parser?.parse()
        let result = NSDictionary.init(object: users, forKey: "result" as NSCopying)
        return result;
        
    }
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        
        currentElement = elementName
        //当elementName是 "User"时,表示开始解析一个新用户了
        if elementName == "User"{
            //创建一个新用户对象
            user = User()
            //保存下id
            user.id = attributeDict["id"]
        }
    }
    func parser(_ parser: XMLParser, foundCharacters string: String) {
        let data = string.trimmingCharacters(in: .whitespacesAndNewlines)
        //接下来每遇到一个字符,将该字符追加到相应的 property 中
        switch currentElement{
        case "name":
            user.name = user.name ?? "" + data
        case "id":
            user.id = user.id ?? "" + data
        default:
            break
        }
        
    }
    
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        //标签User结束时将该用户对象,存入数组容器。
        if elementName == "User"{
            users.append(user)
        }
        
    }

}