如何在Alamofire中快速打印来自post请求的响应的json内容?

时间:2023-02-15 21:14:56

Ok, so I'm using alamofire and the parameters I'm passing are valid. Here is the code so far:

好的,所以我使用的是alamofire,我传递的参数是有效的。这是到目前为止的代码:

Alamofire.request(.POST, "http://mywebservice.com", parameters: myparameters)
.response { (request, response, data, error) in
    if(error != nil){
        print("error= \(error)")
    }else{
        print("there was no error so far ")
        print(data)
        var json = JSON(data!)

        print(json) //prints unknown
        print(json["id"]) //prints null      
        }
    }
}

I tried different things but so far nothing worked. I'm using alamofire and swiftyjson, the response json that comes from webservice is:

我尝试了不同的东西,但到目前为止没有任我正在使用alamofire和swiftyjson,来自webservice的响应json是:

{
  "id": "432532gdsg",
  "username": "gsdgsdg"
}

and I want to print both values separately in case of success. How can I do it?

如果成功,我想分别打印两个值。我该怎么做?

2 个解决方案

#1


3  

Your issue comes from this line:

您的问题来自此行:

var json = JSON(data!)

The JSON() initializer from SwiftyJSON can take several type of inputs.

SwiftyJSON的JSON()初始化程序可以采用多种类型的输入。

When you don't specify the type in the init, SwiftyJSON tries to infer the type itself.

如果未在init中指定类型,SwiftyJSON会尝试推断类型本身。

Unfortunately it sometimes fails silently because it will have misinterpreted the input.

不幸的是,它有时会无声地失败,因为它会误解输入。

So, when using SwiftyJSON with NSData, the solution is to specify the "data:" parameter for the JSON initializer:

因此,当将SwiftyJSON与NSData一起使用时,解决方案是为JSON初始化程序指定“data:”参数:

var json = JSON(data: data!)

#2


1  

Try this

Alamofire.request(.POST, "http://mywebservice.com", parameters : myparameters , encoding : .JSON )
    .responseData{ response in
            let json = JSON(data.response.result.value!)
            print(json)
            let id=json["id"]
            let username=json["username"]
            print(id)
            print(username)          
}

#1


3  

Your issue comes from this line:

您的问题来自此行:

var json = JSON(data!)

The JSON() initializer from SwiftyJSON can take several type of inputs.

SwiftyJSON的JSON()初始化程序可以采用多种类型的输入。

When you don't specify the type in the init, SwiftyJSON tries to infer the type itself.

如果未在init中指定类型,SwiftyJSON会尝试推断类型本身。

Unfortunately it sometimes fails silently because it will have misinterpreted the input.

不幸的是,它有时会无声地失败,因为它会误解输入。

So, when using SwiftyJSON with NSData, the solution is to specify the "data:" parameter for the JSON initializer:

因此,当将SwiftyJSON与NSData一起使用时,解决方案是为JSON初始化程序指定“data:”参数:

var json = JSON(data: data!)

#2


1  

Try this

Alamofire.request(.POST, "http://mywebservice.com", parameters : myparameters , encoding : .JSON )
    .responseData{ response in
            let json = JSON(data.response.result.value!)
            print(json)
            let id=json["id"]
            let username=json["username"]
            print(id)
            print(username)          
}