如何将JSON数据格式化为可动态生成对象属性的C#对象

时间:2018-07-15 04:56:20

标签: c# json mailchimp json-deserialization mailchimp-api-v3.0

我不确定主题是否正确地描述了我的问题,但希望是。

我目前正在从事一个需要与Mailchimp集成的项目,该成员的object属性之一称为“ merge_fields”,它返回键值对的array

Json数据(为简单起见,仅部分返回)如下:

"members": [{
    "id": "9ff9398a92599aca00401da0fb9f0339da",
"email_address": "myemail@mydomain.com",
"unique_email_id": "90ds8927dae",
"email_type": "html",
"status": "subscribed",
"merge_fields": {
    "FNAME": "My FirstName",
        "LNAME": "My LastName",
        "ADDRESS": "My Address",
        "PHONE": "+555 1234 5678",
        "MMERGE5": ""
},
"stats": {
"avg_open_rate": 0,
"avg_click_rate": 0
},
"ip_signup": "",
"timestamp_signup": "",
...

如您所见,“ merge_fields”属性是键对值的数组,其中键是动态设置的,值也是动态设置的,但是我不确定如何在.NET中定义它可以使用deserialized .NET正确NewtonSoft

在我的会员类中,MergeFields属性定义如下:

[JsonProperty("merge_fields")]
public MailchimpMergeFields MergeFields { get; set; }

和我的MailchimpMergeFields类定义如下:

public class MailchimpMergeFields
{
    /// <summary>
    /// An individual merge var and value for a member.
    /// </summary>
    [JsonProperty("merge_fields")]
    public List<KeyValuePair<object, object>> MergeFields { get; set; }

    public MailchimpMergeFields()
    {
        MergeFields = new List<KeyValuePair<object, object>>();
    }
}

问题在于,当数据为deserialized时,它将在merge_fields属性的数组中返回0个元素。

任何想法我如何反序列化:

"merge_fields": {
    "FNAME": "My FirstName",
    "LNAME": "My LastName",
    "ADDRESS": "My Address",
    "PHONE": "+555 1234 5678",
    "MMERGE5": ""
},

到KeyValuePair(或KeyValuePair)列表,并将其存储在.NET类中

谢谢。

1 个答案:

答案 0 :(得分:1)

此json模式很容易转换为字典

[JsonProperty("merge_fields")]
public Dictionary<string, string> MergeFields { get; set; }