1

Suppose I am having one class like -

public class Test
{
   public int id { get; set; } 
   public string name { get; set; }
}

Normal JSON conversion will output like {"id":1,"name":"Souvik"}

If I Put JsonProperty attribute like below in properties, output will be - {"studentId":1,"studentname":"Souvik"}

public class Test
{ 
  [JsonProperty("studentId")]
  public int id { get; set; }

  [JsonProperty("studentname")]
  public string name { get; set; }
}

But I don't want to set this hardcoded name of JsonProperty on id, name property of class and want to set these dynamically. How Can I do that?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
souvik
  • 28
  • 3
  • 1
    What do you mean by "dynamically"? Can you show some usage? How dynamically you want to change the property names, what is the use case? – Guru Stron Sep 07 '20 at 15:14
  • https://stackoverflow.com/questions/44433732/dynamically-change-the-json-property-name-and-serialize/44435284 – Roman Ryzhiy Sep 07 '20 at 15:22
  • I want to set the JsonProperty name dynamically, meaning output may be like {"id":1,"name":"Souvik"} / {"FullID":1,"Fullname":"Souvik"} / anything like this. Noticed that Key name in JSON output is different – souvik Sep 07 '20 at 15:29

1 Answers1

0

Not sure what you want to achieve but you can for example add properties as entries to Dictionary<string, string>, and serialize it:

var test = new Test
{
    id = 1,
    name = "test"
};
var x = new Dictionary<string, object>();
x.Add("studentId", test.id); // dynamically build the key  
x.Add("studentName", test.name); // dynamically build the key 
Console.WriteLine(JsonConvert.SerializeObject(x)); // prints "{"studentId":1,"studentName":"test"}" 
Guru Stron
  • 102,774
  • 10
  • 95
  • 132