在JSON属性名称中使用点表示法(例如"payment.token") [英] Using dot notation in a JSON property name (e.g. "payment.token")
问题描述
我正在处理必须发出API请求的脚本.当前,要发送到API的对象如下所示:
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
}
};
问题在于,API需要以下格式来接收AdditionalData属性:
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"
}
推荐答案
由于您的请求的其余部分似乎都是匿名对象,因此您可以仅使用 Dictionary
:
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" }
}
};
由于您是C#的新手,所以请注意,我正在为字典使用对象初始化器模式,这相当于预先构建字典并将其分配给匿名对象的additionalData
:
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
};
或者,您可以在C#中创建所需的所有类:
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; }
}
这篇关于在JSON属性名称中使用点表示法(例如"payment.token")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!