GVKun编程网logo

iOS开发swift 中json解析(swiftui json)

23

对于iOS开发swift中json解析感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍swiftuijson,并为您提供关于ios–SwiftyJSON字典解析、ios–Swift:使用Alam

对于iOS开发swift 中json解析感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍swiftui json,并为您提供关于ios – SwiftyJSON字典解析、ios – Swift:使用Alamofire和SwiftyJSON处理JSON、ios – 在swift 2中解析json对象、ios – 在swift 3中将json解析为数组的有用信息。

本文目录一览:

iOS开发swift 中json解析(swiftui json)

iOS开发swift 中json解析(swiftui json)

实现工具类:
import Foundation
public class JSONDecoder {
    var value: AnyObject?
    
    ///print the description of the JSONDecoder
    public var description: String {
        return self.print()
    }
    ///convert the value to a String
    public var string: String? {
        return value as? String
    }
    ///convert the value to an Int
    public var integer: Int? {
        return value as? Int
    }
    ///convert the value to an UInt
    public var unsigned: UInt? {
        return value as? UInt
    }
    ///convert the value to a Double
    public var double: Double? {
        return value as? Double
    }
    ///convert the value to a float
    public var float: Float? {
        return value as? Float
    }
    ///treat the value as a bool
    public var bool: Bool {
        if let str = self.string {
            let lower = str.lowercaseString
            if lower == "true" || lower.toInt() > 0 {
                return true
            }
        } else if let num = self.integer {
            return num > 0
        } else if let num = self.double {
            return num > 0.99
        } else if let num = self.float {
            return num > 0.99
        }
        return false
    }
    //get  the value if it is an error
    public var error: NSError? {
        return value as? NSError
    }
    //get  the value if it is a dictionary
    public var dictionary: Dictionary<String,JSONDecoder>? {
        return value as? Dictionary<String,JSONDecoder>
    }
    //get  the value if it is an array
    public var array: Array<JSONDecoder>? {
        return value as? Array<JSONDecoder>
    }
    //pull the raw values out of an array
    public func getArray<T>(inout collect: Array<T>?) {
        if let array = value as? Array<JSONDecoder> {
            if collect == nil {
                collect = Array<T>()
            }
            for decoder in array {
                if let obj = decoder.value as? T {
                    collect?.append(obj)
                }
            }
        }
    }
    ///pull the raw values out of a dictionary.
    public func getDictionary<T>(inout collect: Dictionary<String,T>?) {
        if let dictionary = value as? Dictionary<String,JSONDecoder> {
            if collect == nil {
                collect = Dictionary<String,T>()
            }
            for (key,decoder) in dictionary {
                if let obj = decoder.value as? T {
                    collect?[key] = obj
                }
            }
        }
    }
    ///the init that converts everything to something nice
    public init(_ raw: AnyObject) {
        var rawObject: AnyObject = raw
        if let data = rawObject as? NSData {
            var error: NSError?
            var response: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: &error)
            if error != nil || response == nil {
                value = error
                return
            }
            rawObject = response!
        }
        if let array = rawObject as? NSArray {
            var collect = [JSONDecoder]()
            for val: AnyObject in array {
                collect.append(JSONDecoder(val))
            }
            value = collect
        } else if let dict = rawObject as? NSDictionary {
            var collect = Dictionary<String,JSONDecoder>()
            for (key,val: AnyObject) in dict {
                collect[key as! String] = JSONDecoder(val)
            }
            value = collect
        } else {
            value = rawObject
        }
    }
    ///Array access support
    public subscript(index: Int) -> JSONDecoder {
        get {
            if let array = self.value as? NSArray {
                if array.count > index {
                    return array[index] as! JSONDecoder
                }
            }
            return JSONDecoder(createError("index: \(index) is greater than array or this is not an Array type."))
        }
    }
    ///Dictionary access support
    public subscript(key: String) -> JSONDecoder {
        get {
            if let dict = self.value as? NSDictionary {
                if let value: AnyObject = dict[key] {
                    return value as! JSONDecoder
                }
            }
            return JSONDecoder(createError("key: \(key) does not exist or this is not a Dictionary type"))
        }
    }
    ///private method to create an error
    func createError(text: String) -> NSError {
        return NSError(domain: "JSONJoy", code: 1002, userInfo: [NSLocalizedDescriptionKey: text]);
    }
    
    ///print the decoder in a JSON format. Helpful for debugging.
    public func print() -> String {
        if let arr = self.array {
            var str = "["
            for decoder in arr {
                str += decoder.print() + ","
            }
            str.removeAtIndex(advance(str.endIndex, -1))
            return str + "]"
        } else if let dict = self.dictionary {
            var str = "{"
            for (key, decoder) in dict {
                str += "\"\(key)\": \(decoder.print()),"
            }
            str.removeAtIndex(advance(str.endIndex, -1))
            return str + "}"
        }
        if value != nil {
            if let str = self.string {
                return "\"\(value!)\""
            }
            return "\(value!)"
        }
        return ""
    }
}
///Implement this protocol on all objects you want to use JSONJoy with
public protocol JSONJoy {
    init(_ decoder: JSONDecoder)
}
使用实例:
1.建立数据的发射对象,字段名必须一致啊!列如:
struct UserEntity
 {
    
    var userid: Int?
    var userName: String?
    var name: String?
    var true_name: String?
    var roleid: Int?
    var cellPhone: String?
    var telePhone: String?
    var statusInfo: String?
    var status: Int?
    var guide: Bool?
    var networkId: Int?
    
    var yxb_authority: Int?
    
    init(){}
   
    init(_ decoder: JSONDecoder) {
        userid = decoder["userid"].integer
        userName = decoder["userName"].string
        name = decoder["name"].string
        true_name = decoder["true_name"].string
        roleid = decoder["roleid"].integer
        cellPhone = decoder["cellPhone"].string
        telePhone = decoder["telePhone"].string
        statusInfo = decoder["statusInfo"].string
        status = decoder["status"].integer
        networkId = decoder["networkId"].integer
        guide = decoder["guide"].bool
        
         yxb_authority = decoder["yxb_authority"].integer
    }
}
 struct LoginEntity {
    
    var msgCode: Int?
    var message: String?
    var field: String?
    var data = UserEntity()
    init(){}
    init(_ decoder: JSONDecoder)
    {
        msgCode = decoder["msgCode"].integer
        message = decoder["message"].string
        field = decoder["field"].string
        data = UserEntity(decoder["data"])
    }
}
2.解析:输出对象data为json串,把String->自定义对象
  let data = dataStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:false)
        
  let testJsonStruct:LoginEntity = LoginEntity(JSONDecoder(data!))


ios – SwiftyJSON字典解析

ios – SwiftyJSON字典解析

我试图使用 SwiftyJSON来解析服务器中的一些数据.

例如,假设从服务器返回的JSON是:

{     
 "data":{  
     "id":"92","name":"harry","username":"Hazza"
   },"error":false
}

我想获取用户名字符串,所以为此我使用以下方法获取数据对象:

let data = json["data"].dictionaryValue

然后为了获取我希望能够做的用户名字符串

let username = data["username"].stringValue

但是,这会返回一个错误,说'(String,JSON)没有名为’.stringValue’的成员.

这个看似简单的问题在哪里出错了?

谢谢.

解决方法

你应该做的是:

if let username = json["data"]["username"].string {
    println(username)
}

ios – Swift:使用Alamofire和SwiftyJSON处理JSON

ios – Swift:使用Alamofire和SwiftyJSON处理JSON

这肯定会被问过几次,但我还没有找到正确的答案,尽管我一直很努力.

我使用Alamofire和SwiftyJSON,我的JSON数据看起来像这样:

{
  "528" : {
    "name" : "Name 1","id" : "528","product_id" : null,"visible" : "0","level" : "2"
  },"29" : {
    "name" : "Name 2","id" : "29","visible" : "1","level" : "1"
  },"173" : {
    "name" : "Name 3","id" : "173","143" : {
    "name" : "Name 4","id" : "143",

…使用此代码:

Alamofire.request(.GET,dataURL,parameters: nil,encoding: .JSON)

    .responseJSON { (request,response,jsonData,error) in

        let json = JSON(jsonData!) 

        println(json)

    }

…所以JSON一切都应该没问题

>我如何访问该数据?我的意思是我如何获得名称,ID,product_ids等
>我如何将该数据(名称)放入我的TableViewController?

解决方法

我在我的一个项目中使用了SwiftyJSON和Alamofire.这是我如何使用它.

>创建一个名为APIProtocol的协议.
>使用GET方法设置API类,该方法接受APIProtocol类型的委托.
>设置TableViewController以实现APIProtocol.
>从TableViewController调用API.get()

// Step 1
protocol APIProtocol {
  func didReceiveResult(results: JSON)
}

// Step 2
func get(path: String,parameters: [String: AnyObject]? = nil,delegate: APIProtocol? = nil){
  let url = "\(self.hostname)\(path)"
  NSLog("Preparing for GET request to: \(url)")

  Alamofire.request(.GET,url,parameters: parameters)
    .responseJSON { (req,res,json,error) in
      if(error != nil) {
        NSLog("GET Error: \(error)")
        println(res)
      }
      else {
        var json = JSON(json!)
        NSLog("GET Result: \(json)")

        // Call delegate if it was passed into the call
        if(delegate != nil) {
            delegate!.didReceiveResult(json)
        }
      }
    }
}

// Step 3
class ActivityViewController: UITableViewController,APIProtocol {
  var activityModelList: NSMutableArray = [] // This is the array that my tableView is using.

  ... 

  func didReceiveResult(result: JSON) {
    var activities: NSMutableArray = []

    NSLog("Activity.didReceiveResult: \(result)")

    for (index: String,activity: JSON) in result {

      var activityModel = ActivityModel(
        id: activity["id"].intValue,message: activity["message"].stringValue
      )

      activities.addobject(activityModel)
    }

    // Set our array of new models
    activityModelList = activities

    // Make sure we are on the main thread,and update the UI.
    dispatch_sync(dispatch_get_main_queue(),{
      self.refreshControl!.endRefreshing()
      self.tableView.reloadData()
    })
  }
}

// Step 4
override func viewDidLoad() {
  MyAPI.get("/activities",delegate: self)
}

ios – 在swift 2中解析json对象

ios – 在swift 2中解析json对象

我是iOS和 Swift编程的新手,我正在尝试创建一个解析json对象的方法

我的json如下

{
 status : true;
 data :[
   "url" : "","startDate" : "","endDate" : "",...
]
}

我在swift中的代码是这样的

进口基金会

class SplashResponse {

    let STATUS              = "status";
    let DATA                = "data";

    let URL                 = "Url"
    let CONTACT_NO          = "ContactNo";
    let SPLASH_IMAGE        = "SplashImage";
    let SPLASH_ID           = "SplashId";
    let TITLE               = "Title";
    let NO_VIEW             = "NoView";
    let IS_ACTIVE           = "isActive";
    let START_DATE          = "StartDate";
    let END_DATE            = "EndDate";


    var status : Bool

    var url : String
    var contactNo : String
    var splashImage : String
    var splashId : Int
    var title : String
    var numOfViews : Int
    var isActive : Bool
    var startDate : String
    var endDate : String

    init(data : NSDictionary){

        status      = data[STATUS] as! Bool;

        if (status == true) {

            if let item = data[DATA] as? [String: AnyObject] {

                url         = item[URL] as! String;
                contactNo   = item[CONTACT_NO] as! String;
                splashImage = item[SPLASH_IMAGE] as! String;
                splashId    = item[SPLASH_ID] as! Int;
                title       = item[TITLE] as! String;
                numOfViews  = item[NO_VIEW] as! Int;
                isActive    = item[IS_ACTIVE] as! Bool;
                startDate   = item[START_DATE] as! String;
                endDate     = item[END_DATE] as! String;

            }
        } else {

            url = "";
            contactNo = "";
            splashImage = "";
            splashId = -1;
            title = "";
            numOfViews = -1;
            isActive = false;
            startDate = "";
            endDate = "";
        }
    }
}

我收到了以下错误

Return from initializer without initializing all stored properties

解决方法

您的问题是,如果if let item = …条件失败,编译器不知道如何初始化您的值.

您有两个选项可用于状态条件,但在真正的分支内部,您创建了一个没有其他分支的新条件,因此编译器正确地抱怨未初始化的存储属性.

我的建议是首先安全地解包数据[DATA]而不制作新的范围,然后使用这些值.

ios – 在swift 3中将json解析为数组

ios – 在swift 3中将json解析为数组

我是 swift的新手,我从请求中得到一个json,但我无法解析.我正在尝试获取json信息并创建在mapkit上使用注释的坐标

下面是我回来的json

{
    coord =     [
                {
            islocationactive = 1;
            latitude = "37.8037522";
            locationid = 1;
            locationsubtitle = Danville;
            locationtitle = "Schreiner's Home";
            longitude = "121.9871216";
        },{
            islocationactive = 1;
            latitude = "37.8191921";
            locationid = 2;
            locationsubtitle = "Elementary School";
            locationtitle = Montair;
            longitude = "-122.0071005";
        },{
            islocationactive = 1;
            latitude = "37.8186077";
            locationid = 3;
            locationsubtitle = "Americas Eats";
            locationtitle = "Chaus Restaurant";
            longitude = "-121.999046";
        },{
            islocationactive = 1;
            latitude = "37.7789669";
            locationid = 4;
            locationsubtitle = "Cheer & Dance";
            locationtitle = Valley;
            longitude = "-121.9829908";
        }
    ] }

我尝试解析的代码就是这个

let task = URLSession.shared.dataTask(with: request as URLRequest){
            data,response,error in

            //exiting if there is some error
            if error != nil{
                print("error is \(error)")
                return;
            }

            //parsing the response
            do {
                //converting resonse to NSDictionary
                var teamJSON: NSDictionary!

                teamJSON =  try JSONSerialization.jsonObject(with: data!,options: .mutableContainers) as? NSDictionary
                print(teamJSON)
                //getting the JSON array teams from the response
                let liquidLocations: NSArray = teamJSON["coord"] as! NSArray

                //looping through all the json objects in the array teams
                for i in 0 ..< liquidLocations.count{

                    //getting the data at each index
      //              let teamId:Int = liquidLocations[i]["locationid"] as! Int!

                }

            } catch {
                print(error)
            }
        }
        //executing the task
        task.resume()

但不是我尝试工作.我想得到纬度,经度并在地图上创建一个注释

谢谢您的帮助

解决方法

您可以尝试使用与@Niko Adrianus Yuwono相同的代码,但进行了一些更改,因此您将获得teamid作为整数
do {
        let data : NSData = NSData() // change your data variable as you get from webservice response
        guard let teamJSON =  try NSJSONSerialization.JSONObjectWithData(data,options: []) as? [String: Any],let liquidLocations = teamJSON["coord"] as? [[String: Any]]
            else { return }

        //looping through all the json objects in the array teams
        for i in 0 ..< liquidLocations.count{
            let teamId: Int = (liquidLocations[i]["locationid"] as! Nsstring).integerValue
            print(teamId)
        }

    } catch {
        print(error)
    }

我们今天的关于iOS开发swift 中json解析swiftui json的分享就到这里,谢谢您的阅读,如果想了解更多关于ios – SwiftyJSON字典解析、ios – Swift:使用Alamofire和SwiftyJSON处理JSON、ios – 在swift 2中解析json对象、ios – 在swift 3中将json解析为数组的相关信息,可以在本站进行搜索。

本文标签: