【发布时间】:2015-03-06 09:33:32
【问题描述】:
我使用了一个 API,它要求我根据我发送的所有参数的值使用某种散列算法来计算我的请求的签名。如果签名错误,我的请求将被拒绝。因此,对我来说,列出我要发送的所有参数很重要。
我有一个想要发送的复杂对象:
public class InboundShipmentPlan
{
public InboundShipmentPlan()
{
InboundShipmentPlanRequestItems = new List<InboundShipmentPlanRequestItem>();
}
public Address ShipFromAddress { get; set; }
public string ShipToCountryCode { get; set; }
public string LabelPrepPreference { get; set; }
public List<InboundShipmentPlanRequestItem> InboundShipmentPlanRequestItems { get; set; }
}
public class Address
{
public string Name { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string DistrictOrCounty { get; set; }
public string CountryCode { get; set; }
public string PostalCode { get; set; }
}
public class InboundShipmentPlanRequestItem
{
public string Prop1{ get; set; }
public string Prop2 { get; set; }
public string Condition { get; set; }
public int Quantity { get; set; }
}
这是我正在做的:
InboundShipmentPlanRequestItem item = new InboundShipmentPlanRequestItem
{
Prop1 = "My",
Prop2 = "Zorro",
Quantity = 2
};
Address shipmentPlanShipFromAddress = new Address
{
AddressLine1 = "25 Courtfield Garden",
City = "London",
CountryCode = "UK",
PostalCode = "SW5 OPG",
Name = "The Naddler"
};
InboundShipmentPlan shipmentPlan = new InboundShipmentPlan
{
ShipToCountryCode = "US",
ShipFromAddress = shipmentPlanShipFromAddress
};
shipmentPlan.InboundShipmentPlanRequestItems.Add(item);
var client = new RestClient(endpointAdresss) {Authenticator = new CustomAuthenticator()};
var request = new RestRequest(Method.POST) {Resource = "SomeAction/2010-10-01"};
request.RequestFormat = DataFormat.Json;
request.AddParameter("Action", "CreateInboundShipmentPlan");
//var serializedObject = JsonConvert.SerializeObject(shipmentPlan);
request.AddBody(shipmentPlan);
var response = client.Execute(request);
我正在计算 Authenticator 中的签名。我的问题是 request.AddBody 没有将我的 JSON 对象属性添加到参数列表(request.Parameters)中,因此我的签名是错误的。方法 request.AddObject 确实将它们添加到请求参数列表中,但此方法的问题是对象未序列化,因此复杂属性(地址等)具有如下值:System.Collection.Generic .列表。
我该如何解决这个问题?谢谢
更新
我发现,当我使用AddJsonObject时,它实际上添加了一个名为“application/json”的参数,其值为JSON字符串。但是,我需要的是,如果我有一个包含 2 个字符串属性和一个属性的复杂类型,该属性是长度为 n 的复杂类型的列表,则将 2 + n 个单独的参数添加到请求中,而不仅仅是一个 JSON 字符串。
一种解决方法是解析 JSON 字符串并将其转换为键值字典,但我还没有找到通用实现并且不确定是否值得深入研究。到目前为止,我找到的所有解决方案都是基于这样一个事实,即作者事先知道他试图展平的 JSON 对象的结构。
【问题讨论】: