带有 Alamofire post 参数的 SwiftyJSON 对象

Posted

技术标签:

【中文标题】带有 Alamofire post 参数的 SwiftyJSON 对象【英文标题】:SwiftyJSON object with Alamofire post parameter 【发布时间】:2016-10-11 17:33:42 【问题描述】:

好的。坚持简单的任务,将项目从 AFNetworking swift 2 转换为 Alamofire swift 3。

我有一个 json 对象 (SwiftyJSON),需要作为 body json 参数发送。

这是我的对象:


  "enableSMS" : 1,
  "deviceAssociationID" : 12,
  "timeStamp" : "2016-10-07 23:35:32",
  "userDeviceAccessID" : 1,
  "valueBattery" : 25,
  "deviceDescription" : "<null>",
  "deviceID" : 1,
  "valueTemperature" : 46,
  "valueTRange1" : "0.000000",
  "deviceTypeId" : 1,
  "latitude" : "-23.504236000000000",
  "enableEmail" : 1,
  "valueTiers" : [
    
      "userShareDeviceId" : 6,
      "sharedStatusId" : 1,
      "sharedStatus" : "INVITE_SENT",
      "destUserId" : 60,
      "personEmail" : "eu@you.com",
      "sharedDate" : "2016-08-17 20:57:06",
      "personName" : "Daniel",
      "personPhone" : "+55 11 9999999999",
      "acceptationDate" : null
    ,
    
      "userShareDeviceId" : 7,
      "sharedStatusId" : 1,
      "sharedStatus" : "INVITE_SENT",
      "destUserId" : 1,
      "personEmail" : "x@y.com",
      "sharedDate" : "2016-10-04 20:00:06",
      "personName" : "John",
      "personPhone" : "",
      "acceptationDate" : null
    
  ],
  "enableTimeRange" : 1,
  "deviceVersion" : "0.1",
  "valueSMS" : [
    
      "SMSId" : 1,
      "personName" : "Daniel",
      "personPhone" : "+55 11 999999999"
    
  ],
  "deviceName" : "Vovózinhaaaa",
  "jsonAddress" : "\"place_id\":\"24020287\",\"licence\":\"Data © OpenStreetMap contributors, ODbL 1.0. http:\\\/\\\/www.openstreetmap.org\\\/copyright\",\"osm_type\":\"node\",\"osm_id\":\"2355070909\",\"lat\":\"-23.5038297\",\"lon\":\"-46.6285165\",\"display_name\":\"Itaú Personalité, Avenida Brás Leme, Jardim São Bento, Casa Verde, SP, Microrregião de São Paulo, RMSP, Mesorregião Metropolitana de São Paulo, SP, Região Sudeste, 02022-010, Brasil\",\"address\":\"bank\":\"Itaú Personalité\",\"road\":\"Avenida Brás Leme\",\"neighbourhood\":\"Jardim São Bento\",\"suburb\":\"Casa Verde\",\"city_district\":\"Casa Verde\",\"city\":\"SP\",\"county\":\"Microrregião de São Paulo\",\"state_district\":\"Mesorregião Metropolitana de São Paulo\",\"state\":\"SP\",\"postcode\":\"02022-010\",\"country\":\"Brasil\",\"country_code\":\"br\",\"boundingbox\":[\"-23.5039297\",\"-23.5037297\",\"-46.6286165\",\"-46.6284165\"]",
  "deviceJSONWeather" : "\"coord\":\"lon\":-46.63,\"lat\":-23.47,\"weather\":[\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03n\"],\"base\":\"cmc stations\",\"main\":\"temp\":299.26,\"pressure\":1023,\"humidity\":81,\"temp_min\":299.26,\"temp_max\":299.26,\"wind\":\"speed\":3.08,\"deg\":70,\"gust\":3.08,\"rain\":\"3h\":0.03,\"clouds\":\"all\":36,\"dt\":1470863106,\"sys\":\"type\":3,\"id\":135121,\"message\":0.0091,\"country\":\"BR\",\"sunrise\":1470821690,\"sunset\":1470862123,\"id\":3467431,\"name\":\"Cantareira\",\"cod\":200",
  "acceleration" : "3.89743600",
  "temperature" : "27.00",
  "speed" : "9.000000",
  "valueEmails" : [
    
      "emailId" : 1,
      "personName" : "John Doe",
      "personEmail" : "j@doe.com"
    ,
    
      "emailId" : 2,
      "personName" : "Daniel",
      "personEmail" : "eu@you.com"
    
  ],
  "longitude" : "-46.628792000000000",
  "valueGeoFencing" : [
    
      "geoFencingAnalyseSaturday" : 1,
      "geoFencingLongitude" : "-46.639857300000020",
      "geoFencingName" : "Geo 1",
      "geoFencingAddress" : "Tv. Heliodora, 14",
      "geoFencingLatitude" : "-23.503186700000000",
      "geoFencingTimeRange1" : "0.150000000",
      "geoFencingAnalyseSunday" : 0,
      "geoFencingTimeEnabled" : 0,
      "geoFencingAnalyseMonday" : 1,
      "geoFencingAnalyseTuesday" : 1,
      "geoFencingTypeId" : 1,
      "geoFencingTimeRange2" : "0.750000000",
      "geoFencingId" : 5,
      "geoFencingAnalyseFriday" : 1,
      "geoFencingRadius" : 744,
      "geoFencingAnalyseWednesday" : 0,
      "geoFencingTypeName" : "ENTER",
      "geoFencingAnalyseThursday" : 1
    
  ],
  "enableImpact" : 1,
  "enableGeoFencing" : 1,
  "devicePicture" : "https:\/\/pic.com\/devices\/12.jpg",
  "userID" : 1,
  "enableAlerts" : 1,
  "useTypeDescription" : "SENIOR",
  "enableBattery" : 1,
  "valueSpeed" : 62,
  "batteryLevel" : 73,
  "valueTRange2" : "1.000000",
  "altitude" : "721.900024",
  "enableSpeed" : 1,
  "deviceTimeZoneName" : "(GMT -3:00) Eastern Brazil",
  "heading_to" : "116.839996",
  "enableTemperature" : 1,
  "enableTiers" : 1,
  "deviceStatus" : "ACTIVATED",
  "deviceSerialNumber" : "TRX00001",
  "alertsNonRead" : 69,
  "deviceUseTypeId" : 4,
  "deviceTimeZone" : "America\/Sao_Paulo"

尝试直接发布(转换为参数类型)我的 API 无法识别任何参数。

然后我转换成字典:

do 
    let dic = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
    userDevices.updateUserDevices(settings: dic as! Parameters)  (response, error) in
        print(response)
        print(error)
    
 catch 
    print("error")

调试 Alamofire 帖子我有这个序列化:

"\"enableSMS\":1,\"deviceAssociationID\":12,\"deviceTimeZone\":\"America\/Sao_Paulo\",\"userDeviceAccessID\":1,\"valueBattery\":25,\"deviceDescription\":\"<null>\",\"deviceID\":1,\"valueTemperature\":46,\"valueTRange1\":\"0.000000\",\"deviceTypeId\":1,\"latitude\":\"-23.504236000000000\",\"enableEmail\":1,\"valueTiers\":[\"userShareDeviceId\":6,\"sharedStatusId\":1,\"sharedStatus\":\"INVITE_SENT\",\"destUserId\":60,\"personEmail\":\"eu@daniellombardi.com.br\",\"sharedDate\":\"2016-08-17 20:57:06\",\"personName\":\"Daniel Lombardi\",\"personPhone\":\"+55 11 981378213\",\"acceptationDate\":null,\"userShareDeviceId\":7,\"sharedStatusId\":1,\"sharedStatus\":\"INVITE_SENT\",\"destUserId\":1,\"personEmail\":\"giulio@loffreda.com.br\",\"sharedDate\":\"2016-10-04 20:00:06\",\"personName\":\"Giulio\",\"personPhone\":\"\",\"acceptationDate\":null],\"enableTimeRange\":1,\"deviceVersion\":\"0.1\",\"valueSMS\":[\"SMSId\":1,\"personName\":\"Daniel Lombardi\",\"personPhone\":\"+55 11 981378213\"],\"deviceName\":\"Vovózinhaaaa\",\"userID\":1,\"deviceJSONWeather\":\"\\\"coord\\\":\\\"lon\\\":-46.63,\\\"lat\\\":-23.47,\\\"weather\\\":[\\\"id\\\":802,\\\"main\\\":\\\"Clouds\\\",\\\"description\\\":\\\"scattered clouds\\\",\\\"icon\\\":\\\"03n\\\"],\\\"base\\\":\\\"cmc stations\\\",\\\"main\\\":\\\"temp\\\":299.26,\\\"pressure\\\":1023,\\\"humidity\\\":81,\\\"temp_min\\\":299.26,\\\"temp_max\\\":299.26,\\\"wind\\\":\\\"speed\\\":3.08,\\\"deg\\\":70,\\\"gust\\\":3.08,\\\"rain\\\":\\\"3h\\\":0.03,\\\"clouds\\\":\\\"all\\\":36,\\\"dt\\\":1470863106,\\\"sys\\\":\\\"type\\\":3,\\\"id\\\":135121,\\\"message\\\":0.0091,\\\"country\\\":\\\"BR\\\",\\\"sunrise\\\":1470821690,\\\"sunset\\\":1470862123,\\\"id\\\":3467431,\\\"name\\\":\\\"Cantareira\\\",\\\"cod\\\":200\",\"jsonAddress\":\"\\\"place_id\\\":\\\"24020287\\\",\\\"licence\\\":\\\"Data © OpenStreetMap contributors, ODbL 1.0. http:\\\/\\\/www.openstreetmap.org\\\/copyright\\\",\\\"osm_type\\\":\\\"node\\\",\\\"osm_id\\\":\\\"2355070909\\\",\\\"lat\\\":\\\"-23.5038297\\\",\\\"lon\\\":\\\"-46.6285165\\\",\\\"display_name\\\":\\\"Itaú Personalité, Avenida Brás Leme, Jardim São Bento, Casa Verde, SP, Microrregião de São Paulo, RMSP, Mesorregião Metropolitana de São Paulo, SP, Região Sudeste, 02022-010, Brasil\\\",\\\"address\\\":\\\"bank\\\":\\\"Itaú Personalité\\\",\\\"road\\\":\\\"Avenida Brás Leme\\\",\\\"neighbourhood\\\":\\\"Jardim São Bento\\\",\\\"suburb\\\":\\\"Casa Verde\\\",\\\"city_district\\\":\\\"Casa Verde\\\",\\\"city\\\":\\\"SP\\\",\\\"county\\\":\\\"Microrregião de São Paulo\\\",\\\"state_district\\\":\\\"Mesorregião Metropolitana de São Paulo\\\",\\\"state\\\":\\\"SP\\\",\\\"postcode\\\":\\\"02022-010\\\",\\\"country\\\":\\\"Brasil\\\",\\\"country_code\\\":\\\"br\\\",\\\"boundingbox\\\":[\\\"-23.5039297\\\",\\\"-23.5037297\\\",\\\"-46.6286165\\\",\\\"-46.6284165\\\"]\",\"temperature\":\"27.00\",\"speed\":\"9.000000\",\"valueEmails\":[\"emailId\":1,\"personName\":\"Giulio Loffreda\",\"personEmail\":\"giulio@loffreda.com.br\",\"emailId\":2,\"personName\":\"Daniel Lombardi\",\"personEmail\":\"eu@daniellombardi.com.br\"],\"longitude\":\"-46.628792000000000\",\"valueGeoFencing\":[\"geoFencingAnalyseThursday\":1,\"geoFencingLongitude\":\"-46.639857300000020\",\"geoFencingName\":\"Geo 1\",\"geoFencingAddress\":\"Tv. Heliodora, 14\",\"geoFencingLatitude\":\"-23.503186700000000\",\"geoFencingTimeRange1\":\"0.150000000\",\"geoFencingAnalyseSunday\":0,\"geoFencingTimeEnabled\":0,\"geoFencingAnalyseMonday\":1,\"geoFencingAnalyseTuesday\":1,\"geoFencingTypeId\":1,\"geoFencingTimeRange2\":\"0.750000000\",\"geoFencingId\":5,\"geoFencingAnalyseFriday\":1,\"geoFencingRadius\":744,\"geoFencingAnalyseSaturday\":1,\"geoFencingAnalyseWednesday\":0,\"geoFencingTypeName\":\"ENTER\"],\"enableImpact\":1,\"enableGeoFencing\":1,\"devicePicture\":\"https:\/\/profiles.t-rex.io\/devices\/12.jpg\",\"acceleration\":\"3.89743600\",\"enableAlerts\":1,\"useTypeDescription\":\"SENIOR\",\"enableBattery\":1,\"valueSpeed\":62,\"batteryLevel\":73,\"valueTRange2\":\"1.000000\",\"altitude\":\"721.900024\",\"enableSpeed\":1,\"deviceTimeZoneName\":\"(GMT -3:00) Eastern Brazil\",\"heading_to\":\"116.839996\",\"enableTemperature\":1,\"enableTiers\":1,\"deviceStatus\":\"ACTIVATED\",\"deviceSerialNumber\":\"TRX00001\",\"alertsNonRead\":69,\"deviceUseTypeId\":4,\"timeStamp\":\"2016-10-07 23:35:32\"" \

不符合 json 或 api 的。

这是我的电话:

alamoFireManager?.request("\(urlUserApi)\", method: .post, parameters: settings, encoding: JSONEncoding.default, headers:["Authorization" : userData.apiKey])
            .debugLog()
            .responseJSON(completionHandler:  (response) in
                switch response.result 
                case .success:
                    let useType = JSON(response.result.value!)
                    if ((useType["error"].bool) == true) 
                        let error = NSError(domain: UserErrorDomain, code: -982, userInfo: [NSLocalizedDescriptionKey: translateStrings(useType["message"].string!)])
                        completion(nil, error)
                     else 
                        completion(useType, nil)
                    
                case .failure(let error):
                    completion(nil, error)
                
            )

尝试使用 URLEncoding.default 更改编码(尝试了所有这些)我有这个:

"acceleration=3.89743600&alertsNonRead=69&altitude=721.900024&batteryLevel=73&deviceAssociationID=12&deviceDescription=%3Cnull%3E&deviceID=1&deviceJSONWeather=%7B%22coord%22%3A%7B%22lon%22%3A-46.63%2C%22lat%22%3A-23.47%7D%2C%22weather%22%3A%5B%7B%22id%22%3A802%2C%22main%22%3A%22Clouds%22%2C%22description%22%3A%22scattered%20clouds%22%2C%22icon%22%3A%2203n%22%7D%5D%2C%22base%22%3A%22cmc%20stations%22%2C%22main%22%3A%7B%22temp%22%3A299.26%2C%22pressure%22%3A1023%2C%22humidity%22%3A81%2C%22temp_min%22%3A299.26%2C%22temp_max%22%3A299.26%7D%2C%22wind%22%3A%7B%22speed%22%3A3.08%2C%22deg%22%3A70%2C%22gust%22%3A3.08%7D%2C%22rain%22%3A%7B%223h%22%3A0.03%7D%2C%22clouds%22%3A%7B%22all%22%3A36%7D%2C%22dt%22%3A1470863106%2C%22sys%22%3A%7B%22type%22%3A3%2C%22id%22%3A135121%2C%22message%22%3A0.0091%2C%22country%22%3A%22BR%22%2C%22sunrise%22%3A1470821690%2C%22sunset%22%3A1470862123%7D%2C%22id%22%3A3467431%2C%22name%22%3A%22Cantareira%22%2C%22cod%22%3A200%7D&deviceName=Vov%C3%B3zinhaaaa&devicePicture=https%3A//profiles.t-rex.io/devices/12.jpg&deviceSerialNumber=TRX00001&deviceStatus=ACTIVATED&deviceTimeZone=America/Sao_Paulo&deviceTimeZoneName=%28GMT%20-3%3A00%29%20Eastern%20Brazil&deviceTypeId=1&deviceUseTypeId=4&deviceVersion=0.1&enableAlerts=1&enableBattery=1&enableEmail=1&enableGeoFencing=1&enableImpact=1&enableSMS=1&enableSpeed=1&enableTemperature=1&enableTiers=1&enableTimeRange=1&heading_to=116.839996&jsonAddress=%7B%22place_id%22%3A%2224020287%22%2C%22licence%22%3A%22Data%20%C2%A9%20OpenStreetMap%20contributors%2C%20ODbL%201.0.%20http%3A%5C/%5C/www.openstreetmap.org%5C/copyright%22%2C%22osm_type%22%3A%22node%22%2C%22osm_id%22%3A%222355070909%22%2C%22lat%22%3A%22-23.5038297%22%2C%22lon%22%3A%22-46.6285165%22%2C%22display_name%22%3A%22Ita%C3%BA%20Personalit%C3%A9%2C%20Avenida%20Br%C3%A1s%20Leme%2C%20Jardim%20S%C3%A3o%20Bento%2C%20Casa%20Verde%2C%20SP%2C%20Microrregi%C3%A3o%20de%20S%C3%A3o%20Paulo%2C%20RMSP%2C%20Mesorregi%C3%A3o%20Metropolitana%20de%20S%C3%A3o%20Paulo%2C%20SP%2C%20Regi%C3%A3o%20Sudeste%2C%2002022-010%2C%20Brasil%22%2C%22address%22%3A%7B%22bank%22%3A%22Ita%C3%BA%20Personalit%C3%A9%22%2C%22road%22%3A%22Avenida%20Br%C3%A1s%20Leme%22%2C%22neighbourhood%22%3A%22Jardim%20S%C3%A3o%20Bento%22%2C%22suburb%22%3A%22Casa%20Verde%22%2C%22city_district%22%3A%22Casa%20Verde%22%2C%22city%22%3A%22SP%22%2C%22county%22%3A%22Microrregi%C3%A3o%20de%20S%C3%A3o%20Paulo%22%2C%22state_district%22%3A%22Mesorregi%C3%A3o%20Metropolitana%20de%20S%C3%A3o%20Paulo%22%2C%22state%22%3A%22SP%22%2C%22postcode%22%3A%2202022-010%22%2C%22country%22%3A%22Brasil%22%2C%22country_code%22%3A%22br%22%7D%2C%22boundingbox%22%3A%5B%22-23.5039297%22%2C%22-23.5037297%22%2C%22-46.6286165%22%2C%22-46.6284165%22%5D%7D&latitude=-23.504236000000000&longitude=-46.628792000000000&speed=9.000000&temperature=27.00&timeStamp=2016-10-07%2023%3A35%3A32&useTypeDescription=SENIOR&userDeviceAccessID=1&userID=1&valueBattery=25&valueEmails%5B%5D%5BpersonName%5D=Giulio%20Loffreda&valueEmails%5B%5D%5BpersonEmail%5D=giulio%40loffreda.com.br&valueEmails%5B%5D%5BemailId%5D=1&valueEmails%5B%5D%5BpersonName%5D=Daniel%20Lombardi&valueEmails%5B%5D%5BpersonEmail%5D=eu%40daniellombardi.com.br&valueEmails%5B%5D%5BemailId%5D=2&valueGeoFencing%5B%5D%5BgeoFencingTimeEnabled%5D=0&valueGeoFencing%5B%5D%5BgeoFencingAnalyseFriday%5D=1&valueGeoFencing%5B%5D%5BgeoFencingLongitude%5D=-46.639857300000020&valueGeoFencing%5B%5D%5BgeoFencingAddress%5D=Tv.%20Heliodora%2C%2014&valueGeoFencing%5B%5D%5BgeoFencingId%5D=5&valueGeoFencing%5B%5D%5BgeoFencingAnalyseMonday%5D=1&valueGeoFencing%5B%5D%5BgeoFencingAnalyseWednesday%5D=0&valueGeoFencing%5B%5D%5BgeoFencingAnalyseThursday%5D=1&valueGeoFencing%5B%5D%5BgeoFencingLatitude%5D=-23.503186700000000&valueGeoFencing%5B%5D%5BgeoFencingAnalyseTuesday%5D=1&valueGeoFencing%5B%5D%5BgeoFencingTypeId%5D=1&valueGeoFencing%5B%5D%5BgeoFencingTypeName%5D=ENTER&valueGeoFencing%5B%5D%5BgeoFencingTimeRange1%5D=0.150000000&valueGeoFencing%5B%5D%5BgeoFencingName%5D=Geo%201&valueGeoFencing%5B%5D%5BgeoFencingTimeRange2%5D=0.750000000&valueGeoFencing%5B%5D%5BgeoFencingAnalyseSunday%5D=0&valueGeoFencing%5B%5D%5BgeoFencingRadius%5D=744&valueGeoFencing%5B%5D%5BgeoFencingAnalyseSaturday%5D=1&valueSMS%5B%5D%5BpersonPhone%5D=%2B55%2011%20981378213&valueSMS%5B%5D%5BpersonName%5D=Daniel%20Lombardi&valueSMS%5B%5D%5BSMSId%5D=1&valueSpeed=62&valueTRange1=0.000000&valueTRange2=1.000000&valueTemperature=46&valueTiers%5B%5D%5BuserShareDeviceId%5D=6&valueTiers%5B%5D%5BacceptationDate%5D=%3Cnull%3E&valueTiers%5B%5D%5BsharedStatusId%5D=1&valueTiers%5B%5D%5BpersonPhone%5D=%2B55%2011%20981378213&valueTiers%5B%5D%5BpersonEmail%5D=eu%40daniellombardi.com.br&valueTiers%5B%5D%5BsharedStatus%5D=INVITE_SENT&valueTiers%5B%5D%5BsharedDate%5D=2016-08-17%2020%3A57%3A06&valueTiers%5B%5D%5BdestUserId%5D=60&valueTiers%5B%5D%5BpersonName%5D=Daniel%20Lombardi&valueTiers%5B%5D%5BuserShareDeviceId%5D=7&valueTiers%5B%5D%5BacceptationDate%5D=%3Cnull%3E&valueTiers%5B%5D%5BsharedStatusId%5D=1&valueTiers%5B%5D%5BpersonPhone%5D=&valueTiers%5B%5D%5BpersonEmail%5D=giulio%40loffreda.com.br&valueTiers%5B%5D%5BsharedStatus%5D=INVITE_SENT&valueTiers%5B%5D%5BsharedDate%5D=2016-10-04%2020%3A00%3A06&valueTiers%5B%5D%5BdestUserId%5D=1&valueTiers%5B%5D%5BpersonName%5D=Giulio" \

这应该可以工作,但是因为在这个对象中我有子数组,所以我的后端不能理解为 json 对象。

愚蠢的技巧是它与 AFNetworking 合作。

我错过了什么吗?当然,但是什么? 已经阅读了所有 Alamofire 和 SwiftyJSON 文档并尝试了多种类型的序列化。

编辑:

解决方案:

至少在我的情况下,我更改了一些参数,它就像一个魅力:

alamoFireManager?.request("\(urlUserApi)\", method: .post, parameters: settings.dictionaryValue, encoding: URLEncoding.default, headers:["Authorization" : userData.apiKey, "Content-Type" : "application/x-www-form-urlencoded"])
    .debugLog()
    .responseJSON(completionHandler:  (response) in
        switch response.result 
        case .success:
            let useType = JSON(response.result.value!)
            if ((useType["error"].bool) == true) 
                let error = NSError(domain: UserErrorDomain, code: -982, userInfo: [NSLocalizedDescriptionKey: translateStrings(useType["message"].string!)])
                completion(nil, error)
             else 
                completion(useType, nil)
            
        case .failure(let error):
            completion(nil, error)
        
    )

这成功了:

"Content-Type" : "application/x-www-form-urlencoded"

以及将参数类型从 Parameter 更改为 JSON:

settings: JSON

并将其实现为字典:

settings.dictionaryValue

希望对某人有所帮助

@zombie 的回答很好,只是没有用它来改变我的实施标准。

【问题讨论】:

【参考方案1】:

为了能够在 swift 中将您的 json 作为字符串添加,我将其转换为 http://bernhardhaeussner.de/odd/json-escape/

所以我的代码看起来像这样

let values = "\n  \"enableSMS\" : 1,\n  \"deviceAssociationID\" : 12,\n  \"timeStamp\" : \"2016-10-07 23:35:32\",\n  \"userDeviceAccessID\" : 1,\n  \"valueBattery\" : 25,\n  \"deviceDescription\" : \"<null>\",\n  \"deviceID\" : 1,\n  \"valueTemperature\" : 46,\n  \"valueTRange1\" : \"0.000000\",\n  \"deviceTypeId\" : 1,\n  \"latitude\" : \"-23.504236000000000\",\n  \"enableEmail\" : 1,\n  \"valueTiers\" : [\n    \n      \"userShareDeviceId\" : 6,\n      \"sharedStatusId\" : 1,\n      \"sharedStatus\" : \"INVITE_SENT\",\n      \"destUserId\" : 60,\n      \"personEmail\" : \"eu@you.com\",\n      \"sharedDate\" : \"2016-08-17 20:57:06\",\n      \"personName\" : \"Daniel\",\n      \"personPhone\" : \"+55 11 9999999999\",\n      \"acceptationDate\" : null\n    ,\n    \n      \"userShareDeviceId\" : 7,\n      \"sharedStatusId\" : 1,\n      \"sharedStatus\" : \"INVITE_SENT\",\n      \"destUserId\" : 1,\n      \"personEmail\" : \"x@y.com\",\n      \"sharedDate\" : \"2016-10-04 20:00:06\",\n      \"personName\" : \"John\",\n      \"personPhone\" : \"\",\n      \"acceptationDate\" : null\n    \n  ],\n  \"enableTimeRange\" : 1,\n  \"deviceVersion\" : \"0.1\",\n  \"valueSMS\" : [\n    \n      \"SMSId\" : 1,\n      \"personName\" : \"Daniel\",\n      \"personPhone\" : \"+55 11 999999999\"\n    \n  ],\n  \"deviceName\" : \"Vovózinhaaaa\",\n  \"jsonAddress\" : \"\\\"place_id\\\":\\\"24020287\\\",\\\"licence\\\":\\\"Data © OpenStreetMap contributors, ODbL 1.0. http:\\\\\\/\\\\\\/www.openstreetmap.org\\\\\\/copyright\\\",\\\"osm_type\\\":\\\"node\\\",\\\"osm_id\\\":\\\"2355070909\\\",\\\"lat\\\":\\\"-23.5038297\\\",\\\"lon\\\":\\\"-46.6285165\\\",\\\"display_name\\\":\\\"Itaú Personalité, Avenida Brás Leme, Jardim São Bento, Casa Verde, SP, Microrregião de São Paulo, RMSP, Mesorregião Metropolitana de São Paulo, SP, Região Sudeste, 02022-010, Brasil\\\",\\\"address\\\":\\\"bank\\\":\\\"Itaú Personalité\\\",\\\"road\\\":\\\"Avenida Brás Leme\\\",\\\"neighbourhood\\\":\\\"Jardim São Bento\\\",\\\"suburb\\\":\\\"Casa Verde\\\",\\\"city_district\\\":\\\"Casa Verde\\\",\\\"city\\\":\\\"SP\\\",\\\"county\\\":\\\"Microrregião de São Paulo\\\",\\\"state_district\\\":\\\"Mesorregião Metropolitana de São Paulo\\\",\\\"state\\\":\\\"SP\\\",\\\"postcode\\\":\\\"02022-010\\\",\\\"country\\\":\\\"Brasil\\\",\\\"country_code\\\":\\\"br\\\",\\\"boundingbox\\\":[\\\"-23.5039297\\\",\\\"-23.5037297\\\",\\\"-46.6286165\\\",\\\"-46.6284165\\\"]\",\n  \"deviceJSONWeather\" : \"\\\"coord\\\":\\\"lon\\\":-46.63,\\\"lat\\\":-23.47,\\\"weather\\\":[\\\"id\\\":802,\\\"main\\\":\\\"Clouds\\\",\\\"description\\\":\\\"scattered clouds\\\",\\\"icon\\\":\\\"03n\\\"],\\\"base\\\":\\\"cmc stations\\\",\\\"main\\\":\\\"temp\\\":299.26,\\\"pressure\\\":1023,\\\"humidity\\\":81,\\\"temp_min\\\":299.26,\\\"temp_max\\\":299.26,\\\"wind\\\":\\\"speed\\\":3.08,\\\"deg\\\":70,\\\"gust\\\":3.08,\\\"rain\\\":\\\"3h\\\":0.03,\\\"clouds\\\":\\\"all\\\":36,\\\"dt\\\":1470863106,\\\"sys\\\":\\\"type\\\":3,\\\"id\\\":135121,\\\"message\\\":0.0091,\\\"country\\\":\\\"BR\\\",\\\"sunrise\\\":1470821690,\\\"sunset\\\":1470862123,\\\"id\\\":3467431,\\\"name\\\":\\\"Cantareira\\\",\\\"cod\\\":200\",\n  \"acceleration\" : \"3.89743600\",\n  \"temperature\" : \"27.00\",\n  \"speed\" : \"9.000000\",\n  \"valueEmails\" : [\n    \n      \"emailId\" : 1,\n      \"personName\" : \"John Doe\",\n      \"personEmail\" : \"j@doe.com\"\n    ,\n    \n      \"emailId\" : 2,\n      \"personName\" : \"Daniel\",\n      \"personEmail\" : \"eu@you.com\"\n    \n  ],\n  \"longitude\" : \"-46.628792000000000\",\n  \"valueGeoFencing\" : [\n    \n      \"geoFencingAnalyseSaturday\" : 1,\n      \"geoFencingLongitude\" : \"-46.639857300000020\",\n      \"geoFencingName\" : \"Geo 1\",\n      \"geoFencingAddress\" : \"Tv. Heliodora, 14\",\n      \"geoFencingLatitude\" : \"-23.503186700000000\",\n      \"geoFencingTimeRange1\" : \"0.150000000\",\n      \"geoFencingAnalyseSunday\" : 0,\n      \"geoFencingTimeEnabled\" : 0,\n      \"geoFencingAnalyseMonday\" : 1,\n      \"geoFencingAnalyseTuesday\" : 1,\n      \"geoFencingTypeId\" : 1,\n      \"geoFencingTimeRange2\" : \"0.750000000\",\n      \"geoFencingId\" : 5,\n      \"geoFencingAnalyseFriday\" : 1,\n      \"geoFencingRadius\" : 744,\n      \"geoFencingAnalyseWednesday\" : 0,\n      \"geoFencingTypeName\" : \"ENTER\",\n      \"geoFencingAnalyseThursday\" : 1\n    \n  ],\n  \"enableImpact\" : 1,\n  \"enableGeoFencing\" : 1,\n  \"devicePicture\" : \"https:\\/\\/pic.com\\/devices\\/12.jpg\",\n  \"userID\" : 1,\n  \"enableAlerts\" : 1,\n  \"useTypeDescription\" : \"SENIOR\",\n  \"enableBattery\" : 1,\n  \"valueSpeed\" : 62,\n  \"batteryLevel\" : 73,\n  \"valueTRange2\" : \"1.000000\",\n  \"altitude\" : \"721.900024\",\n  \"enableSpeed\" : 1,\n  \"deviceTimeZoneName\" : \"(GMT -3:00) Eastern Brazil\",\n  \"heading_to\" : \"116.839996\",\n  \"enableTemperature\" : 1,\n  \"enableTiers\" : 1,\n  \"deviceStatus\" : \"ACTIVATED\",\n  \"deviceSerialNumber\" : \"TRX00001\",\n  \"alertsNonRead\" : 69,\n  \"deviceUseTypeId\" : 4,\n  \"deviceTimeZone\" : \"America\\/Sao_Paulo\"\n"


      var data = values.data(using: String.Encoding.utf8, allowLossyConversion: false)

      do 
         var json = try JSONSerialization.jsonObject(with: data!, options: [])

         print(json)

         var request = URLRequest(url: url)
       request.httpMethod = "POST"
       request.setValue("application/json", forHTTPHeaderField: "Content-Type")

       request.httpBody = json

       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)
               
       
      
      catch 
         print(error)
      

【讨论】:

很难弄清楚为什么我的对象不是有效的 json。使用 jsonlint.com 我得到一个有效的 json。这条线试试! JSONSerialization.data(withJSONObject: values) 在 JSON 写入中使用无效的***类型使我的应用程序崩溃。测试 if JSONSerialization.isValidJSONObject(settings) 使我的对象无效,这与我的问题中的 json 完全相同。 它起作用了,你的代码给了我一个有价值的提示……改变了我的方法,像一个魅力一样工作。将编辑我的问题并提出解决方案(正如我实施的那样),但您的代码工作正常。非常感谢您的帮助

以上是关于带有 Alamofire post 参数的 SwiftyJSON 对象的主要内容,如果未能解决你的问题,请参考以下文章

带有嵌套参数的 Alamofire POST 请求不返回任何内容

带有 Swift 3 的 Alamofire 4.3,POST 请求不适用于 URL 参数

使用 alamofire 将带有 JSON 对象和查询参数的 POST 请求发送到 REST Web 服务

发送带有参数的 Alamofire 请求以及 HTTP 正文中的图像

如何在 Alamofire 4.0 中仅使用参数和正文在 swift 中使用 POST 方法发送请求?

带有 MultiPart 表单数据中的参数的图像上传在 Alamofire 4.0 中不起作用