【问题标题】:String to data as JSON Swift3字符串到数据作为 JSON Swift3
【发布时间】:2017-06-13 17:09:28
【问题描述】:

我正在使用 swift3 中的 URLRequest。 为了使用休息服务,我需要在 URLResquest 中添加一个主体,为此我使用这个字符串:

 public func jsonPush() -> String {
    let date = NSDate().addingTimeInterval(60)

    let text: String =
        "{" +
            "\"action\": {" +
            "  \"content\": {" +
            "  \"default\": \"VIP\"" +
            "}," +
            "\"@type\": \"SendLocalMessageAction\"," +
            " \"bgAlert\": { " +
            " }, " +
            " \"contentType\": \"text\\/plain\"" +
            "}," +
            "\"draft\": false, " +
            "\"trigger\": { " +
            "\"time\": "+"\(date.timeIntervalSince1970 * 1000)"+", " +
            "\"@type\": \"TimeTrigger\" " +
            "}, " +
            "\"config\": { " +
            "\"name\": \"Llego el cliente VIP Daniel\" " +
            "}, " +
            "\"audience\": { " +
            "\"type\": \"UserIds\", " +
            "\"ids\": [ " +
            "\"DGHCiwUTbDYnmSOOe7CwKKEB5SA2\", " +
            "\"FgLN69yCR1RzKY23fFdYhTD2HZg1\" " +
            "] " +
            " } " +
    "} "
    print("El json es:\(text) como valor final")
        return text
}

但是当我尝试发送数据时

 var request = URLRequest(url: URL(string: uriNotifications + appId)!)
        request.httpMethod = "POST"
        request.addValue(autenticacion, forHTTPHeaderField: "Authorization")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let session = URLSession.shared
               request.httpBody=jsonPush() as? Data
        session.dataTask(with: request) { data, response, error in
            print("Entered the completionHandler")
                       if(error != nil) {
                print("error")
                return
            }
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                //  let posts = json["posts"] as? [[String: Any]] ?? []
                print("Cantidad")
                print(json)
            } catch let parseError {
                print("parsing error: \(parseError)")
                let responseString = String(data: data!, encoding: .utf8)
                print("raw response: \(responseString)")
            }

回复是:

{ error = "错误请求"; "error_description" = "无法解析 JSON:由于输入结束,没有要映射的内容"; }

但如果我尝试输出:

{"action": { "content": { "default": "VIP"},"@type": “SendLocalMessageAction”、“bgAlert”:{}、“contentType”: “文本/纯文本”},“草稿”:假,“触发器”:{“时间”:1497373512981.26, "@type": "TimeTrigger" }, "config": { "name": "Llego el cliente VIP 丹尼尔”},“观众”:{“type”:“UserIds”,“ids”:[ "DGHCiwUTbDYnmSOOe7CwKKEB5SA2", "FgLN69yCR1RzKY23fFdYhTD2HZg1" ] } }

反响不错:

【问题讨论】:

  • 为什么要手动创建JSON字符串,而不是创建集合类型并使用JSONSerialization.data(with:?然后你甚至可以免费获得Data
  • 因为,我只需要更改一个字段....

标签: json xcode swift3


【解决方案1】:

最有可能在线request.httpBody=jsonPush() as? Data 上的问题jsonPush 返回String 您直接将其类型转换为Data 这是错误的,而不是使用data(using:) 和字符串来获取数据。

request.httpBody = jsonPush().data(using: .utf8)

【讨论】:

  • @DanielORTIZ 欢迎朋友 :)
猜你喜欢
  • 1970-01-01
  • 2018-10-28
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 2011-04-30
  • 2022-06-11
相关资源
最近更新 更多