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

2
  • 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 Commented Aug 1, 2016 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? Commented Aug 1, 2016 at 14:44

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

so I tried but did not work ((Xcode breaks all the code is black and not backlit and does not compile(
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.

1 Comment

This solution is also completely breaks the whole project with error: Command failed due to signal: Segmentation fault: 11
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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.