简体   繁体   English

在Json中生成动态密钥

[英]Generate Dynamic Key in Json

In .net core I would like to generate a json as given below, 在.net核心中,我想生成如下所示的json,

{
    "719A070E-4874-E811-9CCE-02152146006A":{
             "userId":"719A070E-4874-E811-9CCE-02152146006A",
              "Name":"Joe"
         }
}

where 719A070E-4874-E811-9CCE-02152146006A is a Id which varies for every user. 其中719A070E-4874-E811-9CCE-02152146006A是一个ID,该ID因每个用户而异。 How can I define the class to the above json while serialize? 序列化时,如何定义上述json的类?

Regards, Joe 问候乔

You can do this with a Dictionary , the keys are used as JSON keys. 您可以使用Dictionary来做到这一点,这些键用作JSON键。 For example, this uses an anonymous type for the value, but you should probably use a concrete class: 例如,此值使用匿名类型,但是您可能应该使用具体的类:

var data = new Dictionary<string, object>
{
    {
        "719A070E-4874-E811-9CCE-02152146006A",  
        new { userId = "719A070E-4874-E811-9CCE-02152146006A", Name = "Joe" }
    }
};

var json = JsonConvert.SerializeObject(data);
Console.WriteLine(json);

Output is: 输出为:

{"719A070E-4874-E811-9CCE-02152146006A":{"userId":"719A070E-4874-E811-9CCE-02152146006A","Name":"Joe"}} {“ 719A070E-4874-E811-9CCE-02152146006A”:{“ userId”:“ 719A070E-4874-E811-9CCE-02152146006A”,“名称”:“ Joe”}}

For completeness, using a concrete class it would look like this. 为了完整起见,使用一个具体的类看起来像这样。

The class: 班级:

public class User
{
    public Guid userId { get; set; }
    public string Name { get; set; }
}

The Dictionary : Dictionary

var data = new Dictionary<string, object>
{
    {
        "719A070E-4874-E811-9CCE-02152146006A",
        new User 
        { 
            userId = Guid.Parse("719A070E-4874-E811-9CCE-02152146006A"), 
            Name = "Joe" 
        }
    }
};

The question itself is a bit confusing but I'l try to be more as comprehensive as I can. 这个问题本身有点令人困惑,但我会尽我所能。 If you just need to generate a GUID in netcore you can use: 如果只需要在netcore中生成GUID,则可以使用:

 var guid = Guid.NewGuid();

If you need to output the whole JSON string after generating a Guid for the user you could do this: 如果在为用户生成Guid之后需要输出整个JSON字符串,则可以执行以下操作:

  var guid = Guid.NewGuid();
    var user =
    new Dictionary<string, object>
    {
        {
            guid.ToString(),
            new {Userid = guid, Name = "Joe"}
        }
    };
    Console.WriteLine(JsonConvert.SerializeObject(user, Formatting.Indented));

Output is: 输出为:

输出

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

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