0

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 !!)

GoZoner
  • 67,920
  • 20
  • 95
  • 145
  • Your response is an array ob objects so you need to parse as array of User, this can be done using alamofire protocols `ResponseObjectSerializable` and `ResponseCollectionSerializable` – Reinier Melian Aug 01 '16 at 14:44
  • Hi, and welcome to SO! What have you tried so far and where did you fail? If you are already using `Alamofire`, maybe try `AlamofireObjectMapper`? – Losiowaty Aug 01 '16 at 14:44

3 Answers3

2

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

Arnaud Wurmel
  • 480
  • 3
  • 15
0

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.

GoZoner
  • 67,920
  • 20
  • 95
  • 145
0

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 :)

Busata
  • 1,029
  • 1
  • 13
  • 27