简体   繁体   中英

how to parse this json in swift?

I have a request

Alamofire.request(.GET,HttpHelper.baseURL+HttpHelper.tripsURL,encoding:.JSON).responseJSON {
response in 

    var json  = JSON(data: response.data!)
    print(json)
    print(json["res"])
}

followed by the result

{
  "res" : "[{\"name\":\"testName\",\"lastName\":\"testLastName\"},{\"name\":\"testName\",\"lastName\":\"testLastName\"}]",
  "status" : "success",
  "out" : "{\"name\":\"testName\",\"lastName\":\"testLastName\"}"
}
[{"name":"testName","lastName":"testLastName"},{"name":"testName","lastName":"testLastName"}]

how i can set data from res to struct or class User

struct  User  {
    var name : String?
    var lastName : String?
}

please help to solve this problem) thank you very much !!)

You can do something like that

var result: [User]()
for user in json["res"] {
   let userTmp = User(name: user["name"], lastName: user["lastName"])
   result.append(userTmp)
}

Regards

Basically, it would be:

class User {
  var name : String?
  var lastName : String?
}

var theUsers = [User]()

Alamofire.request(.GET,HttpHelper.baseURL+HttpHelper.tripsURL,encoding:.JSON)
  .responseJSON { response in 
    var json  = JSON(data: response.data!)
    print(json)

    theUsers = json["res"].map {
      return User (name: $0["name"], lastName: $0.["lastName"])
    }
  })

However, along the way, you might need some typecasting. For example, maybe replace json["res"] with (json["res"] as Array<Dictionary<String,String>>) in order to keep the type checker and type inferencer happy.

I'm using native Codable protocol to do that:

class MyClass: Codable {

    var int: Int?
    var string: String?
    var bool: Bool?
    var double: Double?
}


let myClass = MyClass()
myClass.int = 1
myClass.string = "Rodrigo"
myClass.bool = true
myClass.double = 2.2

if let json = JsonUtil<MyClass>.toJson(myClass) {
    print(json) // {"bool":true,"string":"Rodrigo","double":2.2,"int":1}

    if let myClass = JsonUtil<MyClass>.from(json: json) {
        print(myClass.int ?? 0) // 1
        print(myClass.string ?? "nil") // Rodrigo
        print(myClass.bool ?? false) // true
        print(myClass.double ?? 0) // 2.2
    }
}


And I created a JsonUtil to help me:

public struct JsonUtil<T: Codable>  {

    public static func from(json: String) -> T? {
        if let jsonData = json.data(using: .utf8) {
            let jsonDecoder = JSONDecoder()

            do {
                return try jsonDecoder.decode(T.self, from: jsonData)

            } catch {
                print(error)
            }
        }

        return nil
    }

    public static func toJson(_ obj: T) -> String? {
        let jsonEncoder = JSONEncoder()

        do {
            let jsonData = try jsonEncoder.encode(obj)
            return String(data: jsonData, encoding: String.Encoding.utf8)

        } catch {
            print(error)
            return nil
        }
    }
}

And if you have some issue with Any type in yours objects. Please look my other answer:

https://stackoverflow.com/a/51728972/3368791

Good luck :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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