Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用url中的数字快速解析JSON url_Json_Swift_Parsing - Fatal编程技术网

使用url中的数字快速解析JSON url

使用url中的数字快速解析JSON url,json,swift,parsing,Json,Swift,Parsing,我需要从api获取信息,但在查询中它看起来像这样: 我的问题是,假设我正在寻找一个特定的大小,我需要为空间添加%20。例如,寻找250g巧克力: . Swift无法识别250g,它给了我一个错误:无效的url字符串。如何创建查询中包含数字的json url 编辑: 我将此URL用于URLSession 我使用以下代码格式化查询中的间距: private func formatSearchKey(key: String)->String{ return key.replacingO

我需要从api获取信息,但在查询中它看起来像这样:

我的问题是,假设我正在寻找一个特定的大小,我需要为空间添加%20。例如,寻找250g巧克力: . Swift无法识别250g,它给了我一个错误:无效的url字符串。如何创建查询中包含数字的json url

编辑:

我将此URL用于URLSession

我使用以下代码格式化查询中的间距:

 private func formatSearchKey(key: String)->String{
    return key.replacingOccurrences(of: " ", with: "%20")
}
例如,当我从查询中删除这些数字时,cookies%20和%20就可以了。当我做像cookies 250g:cookies%20250g这样的事情时,它会给我一个错误

编辑2.0

  private func getJsonUrl(pCode: String, key: String) -> String{
    //Create a function that creates a url based on postal code, and key values that it gets back from my database
    return "\(JSON_URL_BASE)postal_code=\(pCode)&q=\(key)"
}

private func formatPostalCode(pCode: String) -> String{
    return pCode.replacingOccurrences(of: " ", with: "")
}

private func formatSearchKey(key: String)->String{
    return key.replacingOccurrences(of: " ", with: "%20")
}

关键值是我遇到的问题。有时他们会返回一个字符串,比如“饼干和牛奶”,这很有效。但当它返回“饼干250g”时,它不会返回

请显示生成错误的代码:无效url字符串。我们无法通过simple
URL.init(string:)
获得该错误。我更新了问题谢谢更新,但还不够清楚。您能否显示
getJsonUrl(pCode:key:)
的整个定义?您的
JSON\u URL\u BASE
末尾包含
?请认真考虑使用
urlpomponents
构建URL,而不是使用字符串插值和手动转义。
  private func getJsonUrl(pCode: String, key: String) -> String{
    //Create a function that creates a url based on postal code, and key values that it gets back from my database
    return "\(JSON_URL_BASE)postal_code=\(pCode)&q=\(key)"
}

private func formatPostalCode(pCode: String) -> String{
    return pCode.replacingOccurrences(of: " ", with: "")
}

private func formatSearchKey(key: String)->String{
    return key.replacingOccurrences(of: " ", with: "%20")
}