[英]Using dot notation in a JSON property name (e.g. “payment.token”)
I am working on a script that has to make an API request. 我正在处理必须发出API请求的脚本。 Currently, the object to send to the API looks like this:
当前,要发送到API的对象如下所示:
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: 问题是,API需要以下格式来接收extraData属性:
"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"
}
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
: 由于请求的其余部分似乎是一个匿名对象,而不是仅为
AdditionalData
创建类,因此可以使用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
: 既然你说你是新来的C#,请注意,我用的字典,这相当于预先建立的字典并将其分配给anyonymous对象的对象初始化模式
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
};
Alternatively, you could make all of the classes you need in C#: 另外,您可以在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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.