0

我正在向我的后端发送一个 POST 请求,但是我收到了这个错误:

The given data was not valid JSON.",
underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840
"JSON text did not start with array or object and option to allow
 fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array
or object and option to allow fragments not set.})))

这是我用来发送/获取数据的代码:

func fetchDataWithParameters(){

    struct Response: Codable {
        let status: String?
        let error: String?
    }

    let decoder = JSONDecoder()
    HTTP.POST("somelinkhere", parameters: ["date": self.weekDays[self.itemSelectedIndex]]) { response in
        if let error = response.error {
            print("got an error: \(error)")
            return
        }
        do {
            let resp = try decoder.decode(Response.self, from: response.data)
            if let err = resp.error {
                print("got an error: \(err)")
            }
            if let status = resp.status {
                print("completed: \(status)")

            }
        } catch let error {
            print("decode json error: \(error)")
        }
    }
}

使用我的终端,我正在尝试执行手动 POST 请求,我得到了这个:

Admins-MacBook-Pro:hello-world admin$ curl -i -H "Accept: application/json" -H "Content-Type: application/json" somelinkhere
HTTP/1.1 200 OK
Server: openresty/1.9.15.1
Date: Thu, 03 May 2018 23:42:04 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 39
Connection: keep-alive
X-Clacks-Overhead: GNU Terry Pratchett

"{\"name\": \"Timo\", \"age\": \"39\"}"

这让我想知道唯一可能的错误可能是我如何解码 JSON。为什么它还能与终端一起使用?有任何想法吗?

正如@patru 建议的那样,我在此处包含了打印内容:

catch let error {
    print(String(data:response.data, encoding: .utf8)!)
    print("decode json error: \(error)")
}

结果是这样的:

"{\"name\": \"Mergim\", \"age\": \"39\"}"
decode json error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))

好像我像使用 curl 一样获取 JSON,但由于某种原因,swift 不认为它是有效的 JSON?这就是我的 post 方法在后端的样子:

@app.route('/', methods=['GET', 'POST'])
def index():

    jsonData = {"name": "Timo", "age": "39"}
    jsonData1 = {"name": "Mergim", "age": "39"}

    if request.method=='GET':
        return json.dumps(jsonData)

    elif request.method=='POST':
        return json.dumps(jsonData1)

编辑

    jsonData = '{"name": "Timo", "age": "39"}'
    jsonData1 = '{"name": "Mergim", "age": "39"}'

变成:

    jsonData = {"name": "Timo", "age": "39"}
    jsonData1 = {"name": "Mergim", "age": "39"}
4

1 回答 1

0

这是微妙的,但是,不管你信不信,问题出在服务器上!

实际上,您的代码看起来……有点不对劲,但还不错,所以我运行了这个 Playground:

import Cocoa

let jsonData = "{\"name\": \"Mergim\", \"age\": \"39\"}".data(using: .utf8)!

struct Response: Codable {
    let status: String?
    let error: String?
}

struct NameAge: Codable {
    let name: String
    let age: String
}

do {
    let resp = try JSONDecoder().decode(Response.self, from: jsonData)
    print(resp)
    let na = try JSONDecoder().decode(NameAge.self, from: jsonData)
    print(na)
} catch {
    print(error)
}

print(String(data:jsonData, encoding: .utf8)!)

由于您Response的结构与您的数据结构不太匹配,因此我实现NameAge了一些更合适的东西。尽管 的价值Response仍然值得怀疑,但两者仍然会解析。我也很困惑,直到我检查了您的错误消息:它抱怨您数据中的第一个字符!我终于在 Playground 中添加了最后一行,问题变得清晰起来。

您为您的服务器(我猜它是 ruby​​ 或接近它的东西)提供了一个有效String对象,并将其转换为相应的 JSON,该 JSON 仍然仅代表 JSON 中的一个字符串。这解释了您拥有的双引号,而我的 Playground 没有产生。您可能应该提供您的jsonDataas aHash并且服务器将正确转换它(不带双引号)。出于随机原因JSONDecoder,不想解码简单的 JSON 字符串,但这是我的借口。

顺便说一句:您可能希望将类型更改为ageInt一旦您可以正确传递它。

于 2018-05-04T17:21:48.940 回答