简体   繁体   English

如何基于swiftyJson提取的json在swift中创建类的对象?

[英]how can I create objects of my class in swift based on json fetched by swiftyJson?

I have a class as follows: 我的课如下:

import Foundation
import MapKit

class SingleRequest: NSObject, MKAnnotation {

var title: String?
let created: String
let discipline: String
let coordinate: CLLocationCoordinate2D


var items = NSMutableArray()


init(title: String, created: String, discipline: String, coordinate: CLLocationCoordinate2D) {
    self.title = title
    self.created = created
    self.discipline = discipline
    self.coordinate = coordinate

    super.init()
}
}

I also have a json that looks like: 我也有一个看起来像的json:

[{"_id":"56c9d44fbcb42e075f7d49b1",
"username":"Ms. Brynlee Quitzon DDS",
"photo":"photo.jpg",
"number":"one",
"description":"Maiores rerum beatae molestiae autem. Voluptatem magni aspernatur est voluptas.",
"__v":0,
"updated_at":"2016-02-21T15:14:23.123Z",
"created_at":"2016-02-21T15:14:23.116Z",
"location":{
"type":"Point",
"coordinates":[5.300567929507009,44.04127433959841]}
},
etc.

and now I want to fetch all json entries and create SingleRequest object for each of them. 现在,我想获取所有json条目并为每个条目创建SingleRequest对象。

So far I created a method in this class: 到目前为止,我在此类中创建了一个方法:

class func getAllRequests() {
    print("getAllRequests")
    RestApiManager.sharedInstance.getRequests { json in
        let results = json//["username"]
        for (index: String, subJson: JSON) in results {
            let user: AnyObject = JSON.object



            var title = user["description"]
            let created = user["created_at"]
            let discipline = user["number"]

            let latitude = (user[""]).doubleValue
            let longitude = (user[""]).doubleValue
            let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

            return SingleRequest(title: title, created: created!, discipline: discipline!, coordinate: coordinate)


        }
    }
}

And now 2 questions: 现在有两个问题:

1) as you can see above, I left those two fields empty: 1)如上所示,我将这两个字段留为空白:

let latitude = (user[""]).doubleValue
let longitude = (user[""]).doubleValue

that's because I don't know how to refer to the long/lat values from my json, since they are embeded in the coordinates field... 那是因为我不知道如何从我的json引用long / lat值,因为它们嵌入在coordinates字段中...

How can I fill it? 我该如何填充?

2) will this function create needed objects? 2)这个函数会创建所需的对象吗? or should I for example change the declaration to mark some return value: 或者我应该例如更改声明以标记一些返回值:

class func getAllRequests()

? Thanks! 谢谢!

For your first question, you need to first get the array out of user["coordinates"] and then downcast it to Array, user["coordinates"] as? Array<Double> 对于第一个问题,您首先需要从user["coordinates"]取出数组,然后将其向下转换为Array, user["coordinates"] as? Array<Double> user["coordinates"] as? Array<Double>

For your second question, it should return an array of SingleRequest, Array<SingleRequest> 对于第二个问题,它应该返回SingleRequest Array<SingleRequest>

class func getAllRequests() -> Array<SingleRequest> {
    var requests: Array<SingleRequest> = [] 
    RestApiManager.sharedInstance.getRequests { json in
         let results = json//["username"]
         for (index: String, subJson: JSON) in results {
              let user: AnyObject = JSON.object

              var title = user["description"]
              let created = user["created_at"]
              let discipline = user["number"]

              guard let coordinates = user["coordinates"] as? Array<Double> else { print("no lat/long") }

              let latitude = coordinates[0]
              let longitude = coordinates[1]
              let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

              requests.append(SingleRequest(title: title, created: created!, discipline: discipline!, coordinate: coordinate))
        }
    }

    return requests
}
var singleRequestsArray = [SingleRequest]()


class func getAllRequests() {

    RestApiManager.sharedInstance.getRequests { json in

        for (index: String, subJson: JSON) in son {

            let user: AnyObject = subjson.object

            let title = user["description"]
            let created = user["created_at"]
            let discipline = user["number"]

            var coordinate = CLLocationCoordinate2D()

            if let coordinates = user["coordinates"].array{

                let latitude = coordinates.first?).doubleValue
                let longitude = coordinates.array.last?).doubleValue
               coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
            }

        singleRequestsArray.append(SingleRequest(title: title, created: created!, discipline: discipline!, coordinate: coordinate))

        }
    }
}

Hope this will help you! 希望这个能对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用SwiftyJSON(在Swift中)基于JSON对象数组创建对象数组? - How do I create an array of objects based on array of JSON objects using SwiftyJSON (in Swift)? 为什么我不能使用AlamoFire和SwiftyJson快速创建班级对象? - Why I can't create objects of my class in swift using AlamoFire and SwiftyJson? 如何在Swift 4中通过SwiftyJson和Almofire创建多个按钮? - How can I create multiple button by SwiftyJson and Almofire in swift 4? 我如何重写此函数,以便它使用SwiftyJSON而不是JSON.swift? - How can I rewrite this function so that it uses SwiftyJSON instead of JSON.swift? 使用SwiftyJSON将JSON数组反序列化为Swift对象 - Deserialize JSON array to Swift objects using SwiftyJSON 仅当所有记录都在Swift中获取时,如何才能将从json异步获取的记录添加到数组中? - How can I add records fetched asynchronously from json to the array only when all records are fetched in Swift? 如何使用SwiftyJSON从JSON中获取所选元素并将其打印在控制台上? - How can I get selected elements from my JSON using SwiftyJSON and print it on the console? 如何在SwiftyJSON中遍历对象? 不只是迅速 - How can I loop through an object in SwiftyJSON? not just with swift 如何使用SwiftyJSON解析json的特定格式? - how can I parse a specific format of json with SwiftyJSON? 如何使用SwiftyJSON将字符串转换为Swift中的JSON数组? - How to convert a string to JSON Array in Swift with SwiftyJSON?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM