我想使用Alamofire swift 4发布对象数组

时间:2018-04-30 05:24:06

标签: ios post alamofire swift4

这是我试图发布的JSON,它有一个名为Menus的JSON数组,里面有菜单对象

 {  
   "Menus":[  
      {  
         "Id":"5ae03b8e90435721f465050c",
         "Name":"testmenu2"
      },
      {  
         "Id":"5ae03f4490435721f465051b",
         "Name":"menu1"
      }
   ],
   "InStock":true,
   "Pricing":{  
      "Price":1000,
      "SaleEnd":"2018-04-20",
      "SaleStart":"2018-04-20",
      "SalePrice":120
   },
   "Sku":"chickenkoththutest",
   "PreparationTime":{  
      "MinCount":"0",
      "MinTime":"0",
      "AdditionalPerItem":"0"
   },
   "Name":"chickenkoththutest",
   "BusinessId":"5adda52c90435519b0c31aff",
   "Attributes":[  

   ],
   "Cuisines":[  

   ],
   "Description":"none"
}

这是我遵循的方法,但所有其他细节都提交除了对象数组。首先,我将对象转换为字典并将它们附加到数组中。发布单个字典对象是有效的,但是当我将它们附加到数组中并尝试发布它时无法发布。有没有办法使用Alamofire发布对象数组

    func AddMenuItem(deviceToken:String,Name:String,Sku:String,BusinessId:String,Pricing:Pricing,Menus:[Menus],Cuisines:[Cuisines],Attributes:[Attributes],Description:String,Instock:Bool,PreparationTime:PreparationTime,_ completion: @escaping (_ sucsessStatus:String, _ id:String,_ error_type:String)->()) {
    let headers = [
        "Authorization": "Bearer " + deviceToken,
        "Accept": "application/json"
    ]
    var categories = [AnyObject]()
 var attributeList = [AnyObject]()
    var cuisineList = [AnyObject]()
     var options = [AnyObject]()
      for menu in Menus{
            if(Menus.count != 0){
               let Cat: NSMutableDictionary = NSMutableDictionary()
                Cat.setValue(menu._Id, forKey: "Id")
                Cat.setValue(menu.Name, forKey: "Name")
           //  let array = JSON(Cat)
                categories.append(Cat)}
            }

    for cuisine in Cuisines{
        if(Cuisines.count != 0){
            let Cat: NSMutableDictionary = NSMutableDictionary()
            Cat.setValue(cuisine._Id, forKey: "Id")
            Cat.setValue(cuisine.Name, forKey: "Name")
          //  let array = JSON(Cat)
            cuisineList.append(Cat)}
    }

    for attr in Attributes{
        if(Attributes.count != 0){
            let Cat: NSMutableDictionary = NSMutableDictionary()
            Cat.setValue(attr._Id, forKey: "Id")
            Cat.setValue(attr.Name, forKey: "Name")
           // let array = JSON(Cat)
            attributeList.append(Cat)}
    }

    for option in OptioList.options{
        if(OptioList.options.count != 0){
            let Cat: NSMutableDictionary = NSMutableDictionary()
            Cat.setValue(option.price, forKey: "Price")
            Cat.setValue(option.Desc, forKey: "Description")
            Cat.setValue(option.isrequired, forKey: "IsRequired")
            // let array = JSON(Cat)
            options.append(Cat)}
    }


    let prepared: NSMutableDictionary = NSMutableDictionary()

    prepared.setValue(PreparationTime.MinTime, forKey: "MinTime")
    prepared.setValue(PreparationTime.MinCount, forKey: "MinCount")
    prepared.setValue(PreparationTime.AdditionalPerItem, forKey: "AdditionalPerItem")
    //let pre = JSON(prepared)

     let pricingdata: NSMutableDictionary = NSMutableDictionary()
   pricingdata.setValue(Pricing.Price, forKey: "Price")
      pricingdata.setValue(Pricing.SalePrice, forKey: "SalePrice")
      pricingdata.setValue(Pricing.SaleStart, forKey: "SaleStart")
      pricingdata.setValue(Pricing.SaleEnd, forKey: "SaleEnd")
   // let pricingd = JSON(pricingdata)
    let param = [  "Name" : Name,
                   "BusinessId" : BusinessId,
                   "Sku" : Sku,
                   "Menus":categories,
                   "Cuisines":cuisineList,
                   "Attributes":attributeList,
        "Description":Description,
        "PreparationTime": prepared ,
        "Pricing":pricingdata,
        "Customizations":options
       ] as [String : Any]



    self._webApiHelper.SendHttpRequest(params: param as AnyObject, header_obj: headers,  url: "Vendor/Menu/Items/Add", http_method: .post) { (response_value, error) in
        print(response_value)

        if(error != "NO_INT"){
            if(response_value["Message"].string! == "SUCCESS")
            {
                completion(response_value["Message"].string! ,response_value["Id"].string!,"")
            }
            else{
                completion(response_value["Message"].string!,"" ,"")

            }



        }
        else{

            completion( "","",response_value["Message"].string!)
        }
    }//SendHttpRequest
}

这是webapihelper方法

var BASE_URL : String = "http://portal.blueicon.lk/api/"
var TOKEN_URL: String = "http://portal.blueicon.lk/token"


func SendHttpRequest(params: AnyObject, header_obj: [String: String], url:String, http_method:HTTPMethod, completion: @escaping (_ response_value: JSON, _ error_type: String)->()) {

    Alamofire.request(BASE_URL + url, method: http_method, parameters: (params as! [String : Any]) , encoding: URLEncoding.default, headers: header_obj).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success( _ ):

            if let jsonValue = response.result.value {
                let json = JSON(jsonValue)
                completion(json, "")
            }
            break

        case .failure(_):
            print(response.result.error!)
            completion(JSON(response.result.value), "NO_INT")
            //"The Internet connection appears to be offline."
            break

        }
    }//Alamofire

}//SendHttpRequest

1 个答案:

答案 0 :(得分:0)

您的代码中的问题

spring:   
  cloud:
    stream:
      kafka:
        binder:
          brokers: localhost:9092
      bindings:
        email-in:
          destination: email
        email-out:
          destination: email

@SpringBootApplication
@EnableBinding(KafkaQuestionSoApplication.EmailQueues.class)
public class KafkaQuestionSoApplication {
    public static void main(String[] args) {
        SpringApplication.run(KafkaQuestionSoApplication.class, args);
    }

    @Bean
    public ApplicationRunner runner(EmailQueues emailQueues) {
        return new ApplicationRunner() {
            @Override
            public void run(ApplicationArguments args) throws Exception {
                emailQueues.outboundEmails().send(new GenericMessage<String>("Hello"));
            }
        };
    }

    @StreamListener(EmailQueues.INPUT)
    public void handleEmail(String payload) {
        System.out.println("received: " + payload);
    }


    public interface EmailQueues {
        String INPUT = "email-in";
        String OUTPUT = "email-out";

        @Input(INPUT)
        SubscribableChannel inboundEmails();

        @Output(OUTPUT)
        MessageChannel outboundEmails();
    }
}

你不能在参数中传递字典。

<强>解决方案:

您需要将Dictionary转换为JSON字符串,然后只有您的问题将解析为使用此扩展名将您的参数中传递的字符串转换为String。

"Pricing":pricingdata

我希望它能奏效。