0

我正在使用 EasyPost(shipping API) 来获取运费。

我可以对货物进行硬编码,但这对我没有帮助。我需要根据用户选择的内容添加数据。

下面是我的代码。如您所见,我有两批货物目前是硬编码的。我想删除硬编码的货物并在其周围添加一个循环并以这种方式添加货物。我可以通过变量传递包裹类型和权重。

因此,如果用户有 5 个包裹,我想添加 5 个货件。

提前致谢!

List<Dictionary<string, object>> shipments;

 shipments = new List<Dictionary<string, object>>() {
            new Dictionary<string, object>() {
                {"parcel", new Dictionary<string, object>() {{ "predefined_package", "MediumFlatRateBox" },  { "weight", 5 }}}
            },
            new Dictionary<string, object>() {
                {"parcel", new Dictionary<string, object>() {{ "predefined_package", "LargeFlatRateBox" },  { "weight", 15 }}}
            }
        };
parameters = new Dictionary<string, object>() {
            {"to_address", toAddress},
            {"from_address", fromAddress},
            {"reference", "USPS"},
            {"shipments", shipments}
                 };

Order order = Order.Create(parameters);
4

1 回答 1

2

您将遍历您的包列表并将项目添加到您的字典列表中。

List<Package> packages = new List<Package>();
// add your packages here ...

List<Dictionary<string, object>> shipments = new List<Dictionary<string, object>>();
foreach(var p in packages){
    shipments.Add(new Dictionary<string, object>() {
          {"parcel", 
           new Dictionary<string, object>() {
               { "predefined_package", "MediumFlatRateBox" },  
               { "weight", p.Weight }}}
            });
}

这不是问题所在,但是如果您尝试通过 POST JSON 通过 HTTP 与 API 进行通信(据我了解,您的目标是在https://www.easypost.com/docs/api调用 API .html#shipments),这样使用匿名类型的对象会更易读,也更惯用:

var shipments = new List<object>();
foreach(var p in packages){
    shipments.Add(new {
          parcel = new {
              predefined_package = "MediumFlatRateBox",
              weight = p.Weight
          }
    });
}

var parameters = new {
   to_address = toAddress,
   from_address = fromAddress,
   reference = USPS,
   shipments = shipments
};

(抱歉缩进,我没有 IDE)

此外,文档表明 EasyPost 有一个 C# 库,用于您正在尝试做的事情,它已经具有所有正确的类型,因此您不需要到处使用字典。请参阅:https ://github.com/EasyPost/easypost-csharp :

Parcel parcel = new Parcel() {
    length = 8,
    width = 6,
    height = 5,
    weight = 10
};

Shipment shipment = new Shipment() {
    from_address = fromAddress,
    to_address = toAddress,
    parcel = parcel
};
于 2017-04-27T19:57:58.027 回答