使用Alamofire迅速将JSON中的无效顶级类型写入'

时间:2019-04-18 11:37:27

标签: json swift alamofire codable

我印有这样的字串

    ["answers": <__NSArrayI 0x7fb0bce08550>(
{
    qid = 884;
    value =     (
        fSociety
    );
}
)
, "uniqid": t-26963212]

我正在使用这样的Encoder将NSObject转换为Json

let realm = try! Realm()
        let savedExamResponse = realm.object(ofType: SavedExamResponse.self, forPrimaryKey: id)
        answersToSubmit.uniqid = savedExamResponse?.uniqueId

        var answerListToSubmit =  [QuestionAnswersToSubmit]()

        for item in (savedExamResponse?.questionAnswerList)! {
            var answerToSubmit = QuestionAnswersToSubmit()
            answerToSubmit.qid =  item.questionId
            answerToSubmit.value.append(item.selectedOption) 
            answerListToSubmit.append(answerToSubmit)

        }
        let answersToSubmit = SubmitAnswerModel(answers:answerListToSubmit,uniqid:savedExamResponse?.uniqueId)

        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted

        let data = try? encoder.encode(answersToSubmit)
        do {
            if let jsonObj = try JSONSerialization.jsonObject(with: data!, options : .allowFragments) as? [String:AnyObject]
            {
                print(jsonObj) // use the json here
            } else {
                print("bad json")
            }
        } catch let error as NSError {
            print(error)
        }

我需要在API中发送BODY参数,因此每当尝试发送此值时,我都会得到Invalid top-level type in JSON write'。 我正在这样使用Alamofire

let urlString = UrlCollection.submitAnswerUrl + "uniqid=" + answersToSubmit.uniqid! + "&token=" + token

        var objectDictionaries = [NSDictionary]()

        let allObjects = answersToSubmit

        var request = URLRequest(url: URL(string: urlString)!)
        request.httpMethod = "POST"

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


        request.httpBody = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted)

        Alamofire.request(request)
            .responseJSON { response in
               switch response.result {
                case .failure(let error):
                    print(error)

                    if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
                        print(responseString)
                    }
                case .success(let responseObject):
                    print(responseObject)
                }
        }

我无法弄清楚到底是什么错误。是因为JSON格式不正确,如果是的话,我应该如何使它正确。任何帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

我在代码中发现了问题

  request.httpBody = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted)

我没有像序列化已编码的值那样将其传递给request.httpBody,就像这样:request.httpBody = data