问题
I am working on a script that has to make an API request. Currently, the object to send to the API looks like this:
var request = new
{
amount = new
{
currency = amount.Currency,
value = amount.Amount
},
additionalData = new AdditionalData
{
ApplePayToken = paymentToken
}
};
The issue is, the API expects the following format to receive the additionalData property:
"additionalData":{
"payment.token": "some-token"
}
I'm using the following code to try to reformat the object above:
internal partial class AdditionalData
{
[JsonProperty(PropertyName="additionalData.payment.token")]
public string ApplePayToken { get; set; }
}
How can I get this to work? Right now, the code doesn't seem to change anything about the request object. It generates it like this:
"additionalData":{
"ApplePayToken": "some-token"
}
回答1:
Since the rest of your request appears to be an anonymous object, instead of making a class only for AdditionalData
, you could just use a Dictionary:
var request = new
{
amount = new
{
currency = amount.Currency,
value = amount.Amount
},
additionalData = new Dictionary<string, object>
{
{ "payment.token", "some-token" }
}
};
Since you said you're new to C#, note that I'm using the object initializer pattern for the dictionary, which is equivalent to pre-building the dictionary and assigning it to the anyonymous object's additionalData
:
Dictionary<string, object> addtData = new Dictionary<string, object>();
addtData.Add("payment.token", "some-token");
var request = new
{
amount = new
{
currency = amount.Currency,
value = amount.Amount
},
additionalData = addtData
};
Try it online
Alternatively, you could make all of the classes you need in C#:
class Request
{
public Amount amount { get; set; }
public AdditionalData additionalData { get; set; }
}
class Amount
{
public string currency { get; set; }
public decimal value { get; set; }
}
class AdditionalData
{
[JsonProperty("payment.token")]
public string applePayToken { get; set; }
}
Try it online
来源:https://stackoverflow.com/questions/55608234/using-dot-notation-in-a-json-property-name-e-g-payment-token