【问题标题】:How to get json from webservice如何从 web 服务获取 json
【发布时间】:2017-12-29 05:28:42
【问题描述】:

我有网址

http://dev.nsol.sg/projects/sneakers/Api/get_all_news
Method: POST

必需参数:

userid

回复:

success = 0 (error), 1 (success)
message = Description of result if success = 0 then message will have the detail description
data: if success = 1 then we will have complete details of common requirements like All news
newsurl: News Image URL + Concatenate Value of img from DB

这是我尝试从 url 获取 json

func news(userid:Int)
{
    let post_data: NSDictionary = NSMutableDictionary()

    post_data.setValue(userid, forKey: "userid")
    let url:URL = URL(string: news_url)!
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

    var paramString = ""

    for (key, value) in post_data
    {
        paramString = paramString + (key as! String)
    }

    request.httpBody = paramString.data(using: String.Encoding.utf8)

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (
        data, response, error) in

        guard let _:Data = data, let _:URLResponse = response  , error == nil else {

            return
        }

        let json: Any?

        do
        {
            json = try JSONSerialization.jsonObject(with: data!, options: [])
            print("abcnews")
            print(json)
        }
        catch
        {
            return
        }

        guard let server_response = json as? NSDictionary else
        {
            return
        }

    })

    task.resume()
}

json的输出是

Optional({
    data =     (
    );
    message = "Invalid User id";
    success = 0;
})

如何获取有效的 json ?你可以从这个链接下载项目https://drive.google.com/file/d/1YJvAEGbh33eHBIJwt1eLOcuCiJknwY8b/view?usp=sharing

【问题讨论】:

  • message = "Invalid User id" 是这里的问题。

标签: json swift api web-services


【解决方案1】:

这是您更新后的工作代码:

func news(userid: Int) {

    var request = URLRequest(url: URL(string: news_url)!)
    request.httpMethod = "POST"

    //Pass your parameter here
    let postString = "userid=\(userid)"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        guard let data = data, error == nil else {
            print("error=(error)")
            return
        }


        let json: Any?

        do
        {

            json = try JSONSerialization.jsonObject(with: data, options: [])
            print("abcnews")
            //here is your JSON
            print(json)
        }
        catch
        {
            return
        }

        guard let server_response = json as? NSDictionary else
        {
            return
        }
    }
    task.resume()
}

您的代码的问题是您没有正确传递参数。

使用上面的代码,您将得到以下响应:

Optional({
    data =     (
                {
            "created_date" = "2017-11-09 14:58:58";
            "created_on" = "2017-11-09";
            "createdd_by" = 3;
            description = dfdfdsdfsdfs;
            id = 4;
            images = "7a53f87882409c4622a0977d5026038b.jpg";
            product = 12;
            status = 1;
            title = facebook;
            "title_keys" = fac;
            type = News;
        },
                {
            "created_date" = "2017-11-15 14:33:01";
            "created_on" = "2017-11-23";
            "createdd_by" = 3;
            description = dfdfdf;
            id = 7;
            images = "e626b8003e6e08df874e33556e7f6e69.jpg";
            product = 0;
            status = 1;
            title = don;
            "title_keys" = don;
            type = News;
        },
                {
            "created_date" = "2017-11-16 10:34:48";
            "created_on" = "2017-11-13";
            "createdd_by" = 3;
            description = "my first computer";
            id = 8;
            images = "556b1855de039b8d99bc787acd103262.jpg";
            product = 13;
            status = 1;
            title = Dell;
            "title_keys" = dell;
            type = News;
        }
    );
    message = "Success.";
    newsurl = "http://dev.nsol.sg/projects/sneakers/assets/brand_images/thumb/";
    success = 1;
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2014-09-24
    相关资源
    最近更新 更多