简体   繁体   中英

Generate Dynamic Key in Json

In .net core I would like to generate a json as given below,

{
    "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. How can I define the class to the above json while serialize?

Regards, Joe

You can do this with a Dictionary , the keys are used as JSON keys. 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"}}

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 :

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:

 var guid = Guid.NewGuid();

If you need to output the whole JSON string after generating a Guid for the user you could do this:

  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:

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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