来自[String:Any]的JSON格式错误

时间:2017-10-01 17:13:11

标签: ios json swift

我试图在Heroku Node.js上设置服务器并为POST方法设置路由。 这是我的index.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.set('port', (process.env.PORT || 5000));

app.use(bodyParser.raw());
app.use(bodyParser.urlencoded({ extended: false }))

app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.post('/song',  (request, response) => {
  console.log(request.body);
  response.send(request.body);
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

我创建了一个简单的ios应用程序来向我的本地Heroku发送POST请求。

@objc func sendPost() {
        guard let url = URL.init(string: "http://localhost:5000/song") as URL? else {
            return
        }
        var request = URLRequest.init(url: url)
        let text : [String: Any] = ["name": "test Name",
                    "artist": "test Artist",
                    "album": "test Album"]

        let data = try? JSONSerialization.data(withJSONObject: text)

        request.httpBody = data!
        request.httpMethod = "POST"

        let task = URLSession.shared.dataTask(with: request) { (data, resp, error) in
            let responseJSON = try? JSONSerialization.jsonObject(with: data!, options: [])
            print(responseJSON!)
        }
        task.resume()
    }

关于一个问题,当我在Node.js上记录request.body时,我得到了错误的JSON: {' {"专辑":"测试专辑","名称":"测试名称",&#34 ;艺术家":"测试艺术家"}':'' } 我的意思是,我的字典成为空值的关键。为什么会这样?

更新: 问题是通过JSONSerializtaion将Dictionary转换为Data。

let text : [String: Any] = ["name": "Olol",
                    "artist": "OMG",
                    "album": "nonon"]
let data = try? JSONSerialization.data(withJSONObject: text)
print(String(data: data!, encoding: String.Encoding.utf8))

在日志中:

{
    "{\"album\":\"nonon\",\"name\":\"Olol\",\"artist\":\"OMG\"}" = "";
}

为什么我的所有数据都成为空值的键?

0 个答案:

没有答案