2017-06-05 77 views
11

我试图与下面的词典将其转化为JSON字典以JSON正在迅速3

let store = [ 
     "newTask" : [ 
      "project_name": "iOS", 
      "total_time":0, 
      "color":"blue" 
     ] 
    ] 

我连载这个使用下面的代码,然后产生一个HTTP POST请求两次连载使用下列选项-POST要求:

 let jsonData = try? JSONSerialization.data(withJSONObject: store) 

     var request = URLRequest(url: URL(string: "http://localhost:3000/store")!) 
     request.httpMethod = "POST" 
     request.httpBody = jsonData 

我也运行一个JSON服务器https://github.com/typicode/json-server具有以下db.json文件

{ 
"store": [ 
    { 
    "id": 0, 
    "ios": { 
     "project_name": "iOS", 
     "total_time": 0, 
     "color": "blue" 
    } 
    }, 
    { 
    "id": 1, 
    "elm": { 
     "project_name": "elm", 
     "total_time": 0, 
     "color": "blue" 
    } 
    } 
] 
} 

我遇到的问题是,在数据库中最新添加的项目看起来不正确,格式如下:

{ 
    "{\"newTask\":{\"project_name\":\"iOS\",\"total_time\":0,\"color\":\"blue\"}}": "", 
    "id": 10 
}, 

我不清楚,为什么它是连载整个字典的键,然后空字符串作为值。

更新

下面是这个职位的服务器代码:

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
       guard let data = data, error == nil else {             // check for fundamental networking error 
        print("error=\(error)") 
        return 
       } 

       if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
        print("statusCode should be 200, but is \(httpStatus.statusCode)") 
        print("response = \(response)") 
       } 

       do { 
        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] { 
         print(json) 



        } 

       } catch let error { 
        print(error.localizedDescription) 
       } 

      } 
      task.resume() 

作为一个方面说明,我试图通过邮递员束缚这一点,这一切工作OK。附上下面的截图。 enter image description here

任何帮助将不胜感激,谢谢!

+0

@EricAya感谢您的联系,以便迅速获得!我已经更新了上述职位有更新发布的HTTP请求,以及解释说,在邮递员同一请求工作正常。 –

+0

@EricAya使键名称是完全一样的,我改变了它。它似乎对邮差工作正常。问题很可能与HTTP请求或正在发生的序列化有关。 –

回答

2

当你构建你的URLRequest会这条线为您解决问题?

request.setValue("application/json", forHTTPHeaderField: "Content-Type") 

在邮递员您发送它作为应用程序/ JSON所以我希望你需要做同样的在你的SWIFT代码。

+0

完美!没有意识到这一点。我一直在寻找的响应和响应类型设置为应用程序/ JSON这样认为POST请求是相同类型的。这为我解决了! :田田:Thansk! –