带输入消息和发布数据的JSON帖子

时间:2017-09-15 02:45:10

标签: json swift

我尝试使用特定的VIN发布到此API以获取make,model,color options等...当我运行代码时,我在XCode控制台中返回以下数据:

responseString = Optional("      {      \"decoder_messages\" : {      \"service_provider\" : \"DataOne Software, Inc.\",      \"decoder_version\" : \"7.0.1\",      \"decoder_errors\" : [      {         \"error_code\" : \"IQ\",         \"error_message\" : \"Invalid query. Query must be properly formatted JSON.\"         }               ]      },            \"query_responses\" : {            }      }      ")

我猜测错误可能在我的getJSONInput()函数中,但我尝试了许多不同的方法,结果相同。感谢您的帮助,我对此感到非常难过,并阅读了各种文档并使用示例代码。我也曾尝试使用Alamofire,但是将postString作为参数传递出来,所以我想我会尝试这种方法。

@IBAction func postButtonPressed(_ sender: AnyObject) {
       getJSONInput()
       postJSON()
}


func postJSON(){


    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "POST"
    let postString = "client_id=xxx&authorization_code=xxx&decoder_query=\(JSONInput)"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")

        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
    }
    task.resume()
}



func getJSONInput() {
    JSONInput = "{" +
        "decoder_settings : {" +
        "display : full," +
        "version : 7.0.1," +
        "styles : on," +
        "style_data_packs : {" +
        "basic_data : off," +
        "pricing : off," +
        "engines : on," +
        "transmissions : on," +
        "specifications : on," +
        "installed_equipment : on," +
        "optional_equipment : on," +
        "colors : on," +
        "safety_equipment : off," +
        "warranties : off," +
        "fuel_efficiency : off," +
        "green_scores : off," +
        "crash_test : off," +
        "awards : on" +
        "}," +
        "common_data : on," +
        "common_data_packs : {" +
        "basic_data : on," +
        "pricing : on," +
        "engines : on," +
        "transmissions : on," +
        "specifications : on," +
        "installed_equipment : on," +
        "optional_equipment : on," +
        "colors : on," +
        "safety_equipment : on," +
        "warranties : on," +
        "fuel_efficiency : on," +
        "green_scores : on," +
        "crash_test : on," +
        "awards : on" +
        "}" +
        "}," +
        "query_requests : {" +
        "Request-Sample : {" +
        "vin : \(myVIN)," +
        "year : ," +
        "make : ," +
        "model : ," +
        "trim : ," +
        "model_number : ," +
        "package_code : ," +
        "drive_type : ," +
        "vehicle_type : ," +
        "body_type : ," +
        "body_subtype : ," +
        "doors : ," +
        "bedlength : ," +
        "wheelbase : ," +
        "msrp : ," +
        "invoice_price : ," +
        "engine : {" +
        "description : ," +
        "block_type : ," +
        "cylinders : ," +
        "displacement : ," +
        "fuel_type :" +
        "}," +
        "transmission : {" +
        "description : ," +
        "trans_type : ," +
        "trans_speeds :" +
        "}," +
        "optional_equipment_codes : ," +
        "installed_equipment_descriptions : ," +
        "interior_color : {" +
        "description : ," +
        "color_code :" +
        "}," +
        "exterior_color : {" +
        "description : ," +
        "color_code :" +
        "}" +
        "}" +
        "}" +
    "}"


}

1 个答案:

答案 0 :(得分:0)

这是我遇到同样问题的人的解决方案

import UIKit
import SwiftyJSON
import Alamofire

class API {



static func getData(completion: @escaping (_ datas: JSON?) -> Void){


    let url = "https://myapiurl"

    let query = "{ \"decoder_settings\" : { \"display\" : \"full\", \"version\" : \"7.0.1\", \"styles\" : \"on\", \"style_data_packs\" : { \"basic_data\" : \"on\", \"pricing\" : \"on\", \"engines\" : \"on\", \"transmissions\" : \"on\", \"specifications\" : \"on\", \"installed_equipment\" : \"on\", \"optional_equipment\" : \"off\", \"colors\" : \"on\", \"safety_equipment\" : \"on\", \"warranties\" : \"on\", \"fuel_efficiency\" : \"on\", \"green_scores\" : \"on\", \"crash_test\" : \"on\", \"awards\" : \"on\" }, \"common_data\" : \"on\", \"common_data_packs\" : { \"basic_data\" : \"on\", \"pricing\" : \"on\", \"engines\" : \"on\", \"transmissions\" : \"on\", \"specifications\" : \"on\", \"installed_equipment\" : \"on\", \"optional_equipment\" : \"on\", \"colors\" : \"on\", \"safety_equipment\" : \"on\", \"warranties\" : \"on\", \"fuel_efficiency\" : \"on\", \"green_scores\" : \"on\", \"crash_test\" : \"on\", \"awards\" : \"on\" } }, \"query_requests\" : { \"Request-Sample\" : { \"vin\" : \"myVINwasHERE\", \"year\" : \"\", \"make\" : \"\", \"model\" : \"\", \"trim\" : \"\", \"model_number\" : \"\", \"package_code\" : \"\", \"drive_type\" : \"\", \"vehicle_type\" : \"\", \"body_type\" : \"\", \"body_subtype\" : \"\", \"doors\" : \"\", \"bedlength\" : \"\", \"wheelbase\" : \"\", \"msrp\" : \"\", \"invoice_price\" : \"\", \"engine\" : { \"description\" : \"\", \"block_type\" : \"\", \"cylinders\" : \"\", \"displacement\" : \"\", \"fuel_type\" : \"\" }, \"transmission\" : { \"description\" : \"\", \"trans_type\" : \"\", \"trans_speeds\" : \"\" }, \"optional_equipment_codes\" : \"\", \"installed_equipment_descriptions\" : \"\", \"interior_color\" : { \"description\" : \"\", \"color_code\" : \"\" }, \"exterior_color\" : { \"description\" : \"\", \"color_code\" : \"\" } } } } "



    let params: [String: Any] = [
        "client_id": "xxx",
        "authorization_code": "xxx123",
        "decoder_query": query
    ]


    Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseString{
        response in

        switch response.result{
        case .success(let data):

            let dic = JSON.parse(data)
            completion(dic)

            break;
        case .failure(let err):
            print(err)
            break;
        }
    }
}

static func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}
}