简体   繁体   English

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

[英]C# object to json - how to build object?

How would the C# object look, o after serialisation json it looks like this? C#对象的外观如何,o序列化json后看起来像这样吗? Already spent few hours on it and cannot figure out how to have email as variable? 已经花了几个小时,无法弄清楚如何将电子邮件作为变量? there will be only one "prospects" and multiple children. 只有一个“前景”和多个孩子。

{
    "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"
        }
    }
}

final result should be 最终结果应该是

Your problem is your "keys" are dynamic. 您的问题是您的“键”是动态的。 This means you cannot hard code it. 这意味着您不能对其进行硬编码 Try this: 尝试这个:

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; }
}

From there you can build your object like this: 从那里可以构建您的对象,如下所示:

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" }},
    }
};

Which results in this Json: 结果就是这个Json:

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

Fiddle here 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM