在JSON属性名称中使用点表示法(例如“ payment.token”)

时间:2019-04-10 08:40:36

标签: c# object json.net

我正在处理必须发出API请求的脚本。当前,要发送到API的对象如下所示:

var request = new
{
    amount = new
    {
        currency = amount.Currency,
        value = amount.Amount
    },
    additionalData = new AdditionalData
    {
        ApplePayToken = paymentToken
    }
};

问题是,API需要以下格式来接收AdditionalData属性:

"additionalData":{
    "payment.token": "some-token"
}

我正在使用以下代码尝试重新格式化上面的对象:

internal partial class AdditionalData
{
    [JsonProperty(PropertyName="additionalData.payment.token")]
    public string ApplePayToken { get; set; }
}

我该如何使用它?目前,该代码似乎并未更改请求对象的任何内容。它是这样生成的:

"additionalData":{
    "ApplePayToken": "some-token"
}

1 个答案:

答案 0 :(得分:3)

由于请求的其余部分似乎是一个匿名对象,而不是仅为Id Policy_id Start_Date Last_dup 0 b123 2019/02/24 0 1 b123 2019/03/24 0 2 b123 2019/04/24 1 3 c123 2018/09/01 0 4 c123 2018/10/01 1 5 d123 2017/02/24 0 6 d123 2017/03/24 1 创建一个类,因此您可以使用Dictionary

AdditionalData

由于您是C#的新手,请注意,我正在为字典使用对象初始化器模式,这相当于预先构建字典并将其分配给匿名对象的var request = new { amount = new { currency = amount.Currency, value = amount.Amount }, additionalData = new Dictionary<string, object> { { "payment.token", "some-token" } } }; :< / p>

additionalData

Try it online

或者,您可以在C#中创建所需的所有类:

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