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?

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? Commented Sep 7, 2020 at 15:14
  • stackoverflow.com/questions/44433732/… Commented Sep 7, 2020 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 Commented Sep 7, 2020 at 15:29

1 Answer 1

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"}" 
Sign up to request clarification or add additional context in comments.

1 Comment

This one helped me. thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.