C#对象到JSON-如何构建对象?

时间:2018-08-30 19:14:27

标签: c# json serialization

C#对象的外观如何,在序列化json后看起来像这样吗? 已经花了几个小时,无法弄清楚如何将电子邮件作为变量?只有一个“前景”和多个孩子。

{
    "prospects": {
        "1234": {
            "first_name": "New first name",
            "last_name": "New last name"
        },
        "some@email.com": {
            "first_name": "New first name",
            "last_name": "New last name"
        },
        "some.other@email.com": {
            "first_name": "New first name",
            "last_name": "New last name"
        }
    }
}

最终结果应该是

1 个答案:

答案 0 :(得分:2)

您的问题是您的“键”是动态的。这意味着您不能硬编码。试试这个:

public class RootObject
{
    [JsonProperty("prospects")]
    public Dictionary<string, NameModel> Prospects { get; set; }
}

public class NameModel
{
    [JsonProperty("firstName")]
    public string FirstName { get; set; }
    [JsonProperty("lastName")]
    public string LastName { get; set; }
}

从那里您可以像这样构建对象:

var model = new RootObject()
{
    Prospects = new Dictionary<string, NameModel>()
    {
        { "1234", new NameModel() { FirstName = "Sam", LastName = "Test" }},
        { "some@email.com", new NameModel() { FirstName = "Sue", LastName = "Test" }},
        { "some.other@email.com", new NameModel() { FirstName = "Frank", LastName = "Test" }},
    }
};

导致此Json发生的原因:

{
    "prospects": {
        "1234": {
            "firstName": "Sam",
            "lastName": "Test"
        },
        "some@email.com": {
            "firstName": "Sue",
            "lastName": "Test"
        },
        "some.other@email.com": {
            "firstName": "Frank",
            "lastName": "Test"
        }
    }
}

提琴here