简体   繁体   English

如何将另一个数组中的数组存储到Swift中从JSON传递的全局变量中?

[英]How to store an array that is within an another array to a global variable that has been passed from JSON in Swift?

I have a JSON which receives an array from an API call 我有一个从API调用接收数组的JSON

Within that array are 3 other arrays: 该数组中还有其他3个数组:

userDetails , userStats , communities userDetailsuserStatscommunities

An example of this API call is: 此API调用的示例是:

["communities": <__NSArrayI 0x6000002540a0>(
{
id = 5;
name = South;
},
{
id = 13;
name = HurraHarry;
},
{
id = 15;
name = EnclliffeT;
}
)
, "userStats": {
totalDraws = 3;
totalLosses = 10;
totalWins = 1;
}, "userDetails": {
id = 31;
"user_email" = "steve@gmail.com";
"user_name" = "Steve Base";
}]

I would like to store the array userStats in a variable that I can pass to another VC. 我想将数组userStats存储在一个可以传递给另一个VC的变量中。

I have a global variable var userStatsArray = [AnyObject]() in my class 我的var userStatsArray = [AnyObject]()有一个全局变量var userStatsArray = [AnyObject]()

and the following code deals with the JSON: 下面的代码处理JSON:

 let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
                  print (json!)

                  if let arr = json?["communities"] as? [[String:String]] {
                        self.communitiesArray = arr.flatMap { $0["name"]!}
                        self.communityIdsArray = arr.flatMap { $0["id"]!}

                    }

                    if let dict = json?["userDetails"] as? [String:String] {
                      self.tempPlayerId = [dict["id"]!]
                        let characterArray = self.tempPlayerId.flatMap { String.CharacterView($0) }
                        let newPlayerId = String(characterArray)
                        self.playerId = newPlayerId
                    }
                    if  let tempArray = json?["userStats"] as? [String:AnyObject]{
                        print ("here ", tempArray)

                    }

The print command successfully prints the userStats array with all its headers (totalWins, totalDraws, totalLosses...) - print命令成功打印出userStats数组及其所有标题(totalWins,totalDraws,totalLosses ...)-

How do I store this array into my global variable var userStatsArray = [AnyObject]() so I can pass it to another VC? 如何将该数组存储到全局变量var userStatsArray = [AnyObject]()以便将其传递给另一个VC?

Better you create one custom class like this, and declare the array with that custom class type. 最好创建一个这样的自定义类,然后使用该自定义类类型声明数组。 then you cast your userStats object to your custom class type. 然后将userStats对象转换为自定义类类型。

class userStats: NSObject {

var totalDraws: NSNumber?
var totalLosses: NSNumber?
var totalWins: NSNumber?

    init(totalDraws: NSNumber?, totalLosses: NSNumber?, totalWins: NSNumber?) {
        self.totalDraws = totalDraws
        self.totalWins = totalWins
        self.totalLosses = totalLosses
    }

}

var userStatsArray = [userStats]()

// CHANGE YOUR CODE LIKE THIS //更改代码,例如

let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
              print (json!)

              if let arr = json?["communities"] as? [[String:String]] {
                    self.communitiesArray = arr.flatMap { $0["name"]!}
                    self.communityIdsArray = arr.flatMap { $0["id"]!}

                }

                if let dict = json?["userDetails"] as? [String:String] {
                  self.tempPlayerId = [dict["id"]!]
                    let characterArray = self.tempPlayerId.flatMap { String.CharacterView($0) }
                    let newPlayerId = String(characterArray)
                    self.playerId = newPlayerId
                }
                if  let tempArray = json?["userStats"]as? userStats {

                    userSytatsArray.append(tempArray)
                }

Take a look at ObjectMapper ! 看看ObjectMapper With that powerful framework you can create the mappable models of your data returned by the API and let it perform the whole work for you :) 有了这个功能强大的框架,您可以为API返回的数据创建可映射的模型,并让它为您执行整个工作:)

Declare your model classes like this: 像这样声明您的模型类:

class UserInfo: Mappable {
var communities : [Community]?
var stats: UserStats?
var details: UserDetails?

required init?(map: Map) {
}

func mapping(map: Map) {
    communities <- map["communities"]
    stats <- map["userStats"]
    details <- map["userDetails"]
 }
}

class Community: Mappable {
var id: Int!
var name: String!

required init?(map: Map) {
}

func mapping(map: Map) {
    id <- map["id"]
    name <- map["name"]
 }
}

class UserStats: Mappable {
var totalDraws : Int!
var totalLosses : Int!
var totalWins : Int!

required init?(map: Map) {
}

func mapping(map: Map) {
    totalDraws <- map["totalDraws"]
    totalLosses <- map["totalLosses"]
    totalWins <- map["totalWins"]
 }
}

class UserDetails: Mappable {
var id : Int!
var email : String!
var username : String!

required init?(map: Map) {
}

func mapping(map: Map) {
    id <- map["id"]
    email <- map["user_email"]
    username <- map["user_name"]
 }
}

And later just: 然后只是:

let user = UserInfo(JSONString: JSONString)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM