JSON错误:NSInvalidArgumentException原因在Swift3 iOS

时间:2018-05-18 09:38:49

标签: ios json post swift3 nsjsonserialization

我在尝试将数据发布到服务器时遇到此异常:

  

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'*** + [NSJSONSerialization   dataWithJSONObject:options:error:]:JSON中的顶级类型无效   写“

这是我的实体类:

class RequestModel {

    var CompanyId: Int? = 0
    var RollupYear: Int? = 0
    var UserId: Int? = 0

    var dataRollupArr:[DataRollupModel]?
    var seasonalityArr:[SeasonalityModel]?
}

class DataRollupModel {

    var Name: String? = ""
    var CurrentValue: Float? = 0.0
    var RollupYear: Int? = 0
    var DataRollupColumnID: Int? = 0
}

class SeasonalityModel {

    var CompanyPeriodId: Int? = 0
    var UserId: Int? = 0
    var Seasonality: String? = ""
}

此处设置值和服务器方法:

func createJSONFromMadal(){

        let resqM = RequestModel()
        resqM.dataRollupArr = [DataRollupModel]()
        resqM.seasonalityArr = [SeasonalityModel]()

        let rollupYear = Int(self.lblYear.text!)
        let userId = UserDefaults.standard.value(forKey: "userid") ?? 0
        let companyId = UserDefaults.standard.value(forKey: "companyid") ?? 0

        resqM.CompanyId = companyId as? Int
        resqM.RollupYear = rollupYear
        resqM.UserId = userId as? Int

        //For DataRollupModel
        for i in 0..<self.responseModel.dataRollupValuesArray.count {

        let dataRollup = responseModel.dataRollupValuesArray[i] as! DataRollupValuesModel

        let r1 = DataRollupModel()

        r1.Name = dataRollup.name
        r1.CurrentValue = dataRollup.currentValue
        r1.RollupYear = rollupYear

        resqM.dataRollupArr?.append(r1)
        }


        //For SeasonalityModel
        for i in 0..<self.responseModel.seasonalityDataResponseArray.count {

            let seasonalityData = responseModel.seasonalityDataResponseArray[i] as! SeasonalityDataResponseModel

            let s1 = SeasonalityModel()
            s1.CompanyPeriodId = seasonalityData.id
            s1.UserId = userId as? Int
            s1.Seasonality = seasonalityData.seasonality

            resqM.seasonalityArr?.append(s1)
        }

        //server code
        do {

            HUDIndicatorView.shared.showHUD(view: self.view,
                                            title: "Loading ..")

            DispatchQueue.global(qos: .userInitiated).async {

                let servicemodel = ServiceModel()

                servicemodel.saveGoal(requestModel: resqM) { returnstring in
                    print(returnstring)

                    DispatchQueue.main.async {

                        HUDIndicatorView.shared.dismissHUD()


                    }
                }
            }

        } catch {

            handleError(error: error)
        }

    }

我的API调用:

func saveGoal(requestModel:RequestModel,  completion:@escaping (NSDictionary) -> ()) {

        if let url = NSURL(string: baseurl+"Save") {
            let request = NSMutableURLRequest( url: url as URL)

            request.httpMethod = "POST"

            let myDict = requestModel

            let jsonData = try! JSONSerialization.data(withJSONObject: myDict, options: [])//CRASHING HERE

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

            request.httpBody = jsonData
            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                data, response, error in
                do{
                    if let data = data,
                        let jsonString =  try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                        , error == nil {
                        completion(jsonString)
                        print(jsonString)
                    } else {
                        print("error=\(error!.localizedDescription)")
                        let errorDict = ["error_status":true,"message":error!.localizedDescription] as [String : Any]
                        completion(errorDict as NSDictionary)

                    }
                }
                catch{
                    print("error=\(error.localizedDescription)")
                    let errorDict = ["error_status":true,"message":error.localizedDescription] as [String : Any]
                    completion(errorDict as NSDictionary)

                }

            }
            task.resume()
        }
    }

我必须传递以下格式的JSON请求:

{
    "CompanyId": 162,
    "RollupYear": 2018,
    "UserId": 1609,
    "datarollup": [{
            "Name": "My Cards",
            "RollupYear": 2018,
            "DataRollupColumnID": 210,
            "CurrentValue": 520
        },
        {
            "Name": "Pros calls",
            "RollupYear": 2018,
            "DataRollupColumnID": 212,
            "CurrentValue": 1300
        }
    ],
    "Seasonalitylist": [{
            "CompanyPeriodId": 386,
            "UserId": 1609,
            "Seasonality": 25
        },
        {
            "CompanyPeriodId": 387,
            "UserId": 1609,
            "Seasonality": 25
        }
    ]
}

请帮助我了解如何在我的代码中添加数组标题标题"datarollup""Seasonalitylist"? 任何人都可以建议我如何解决此错误?

谢谢!

1 个答案:

答案 0 :(得分:1)

创建Encodable类,如下所示,

class RequestModel : Encodable {
    var CompanyId: Int? = 0
    var RollupYear: Int? = 0
    var UserId: Int? = 0
}

现在,您可以按照

创建相同的JSON String
let myStruct = RequestModel()
myStruct.CompanyId = 5
myStruct.RollupYear = 2018
myStruct.UserId = 108

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(myStruct)
print(String(data: data, encoding: .utf8)!)

输出将在下面,

{
  "UserId" : 108,
  "CompanyId" : 5,
  "RollupYear" : 2018
}

希望这对你有所帮助。

<强> FYI 即可。这只是你的参考。请根据您的要求更新全班结构。

<强>更新

像这样使用JsonSerializerSwift库,

class RequestModel {
    var CompanyId: Int? = 0
    var RollupYear: Int? = 0
    var UserId: Int? = 0
    var dataRollupArr = [DataRollupModel]()
}

class DataRollupModel {
    var Name: String? = ""
    var CurrentValue: Float? = 0.0
    var RollupYear: Int? = 0
    var DataRollupColumnID: Int? = 0
}

我在下面实施,

let myStruct = RequestModel()
myStruct.CompanyId = 5
myStruct.RollupYear = 2018
myStruct.UserId = 108

for i in 0...2 {
    let rollUpModel = DataRollupModel()
    rollUpModel.Name = "Test \(i)"
    rollUpModel.CurrentValue = 25.5
    rollUpModel.DataRollupColumnID = 5
    rollUpModel.RollupYear = 2015
    myStruct.dataRollupArr.append(rollUpModel)
}

let json = JSONSerializer.toJson(myStruct)
print(json)

输出就是这个,

{"CompanyId": 5, "RollupYear": 2018, "UserId": 108, "dataRollupArr": [{"Name": "Test 0", "CurrentValue": 25.5, "RollupYear": 2015, "DataRollupColumnID": 5}, {"Name": "Test 1", "CurrentValue": 25.5, "RollupYear": 2015, "DataRollupColumnID": 5}, {"Name": "Test 2", "CurrentValue": 25.5, "RollupYear": 2015, "DataRollupColumnID": 5}]}

http://json.parser.online.fr/输出将如下所示,

enter image description here