Joe Samraj
Joe Samraj

Reputation: 331

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

Upvotes: 0

Views: 368

Answers (2)

greyhame
greyhame

Reputation: 274

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:

output

Upvotes: 2

DavidG
DavidG

Reputation: 119076

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

Upvotes: 4

Related Questions