3

I am trying to create the JSON data using NewtonSoft in c#. I'm using following code-

[JsonProperty(PropertyName = "student")]
public List<Student> obj{ get; set; }

which will create the list of JSON object for students. I wondered, is there any option to give the PropertyName dynamically, like here I'm using PropertyName = "student", I want take name dynamically.

For Example I want following JSON Data-

{
"id": "123",
 "st1": [
 {
  "Name": "chinna",
  },
 ],
 "st2": [
  {
  "Name": "krishan",
 },
 ]
 }

where st1 and st1 are PropertyName which I want to take dynamically.

Chinna Rao
  • 31
  • 3
  • 1
    It's not clear to me what you are trying to do. Please post an example of what you want the serialized version to look like so we can better understand the requirement. – JuanR Oct 27 '16 at 15:06
  • 3
    Possible duplicate of [Overwrite Json property name in c#](http://stackoverflow.com/questions/26882986/overwrite-json-property-name-in-c-sharp) – Nico Oct 27 '16 at 15:07
  • Probably, you can serialize `Dictionary` and thus give your properties whatever the names needed. – Andrew Sklyarevsky Oct 27 '16 at 15:07
  • Take the name dynamically from where? Why would you want to change the name of the property at runtime? – Dave Swersky Oct 27 '16 at 15:08
  • @DaveSwersky, I have update question please check – Chinna Rao Oct 27 '16 at 15:15
  • You cannot achieve it using a decorator attribute as you have shown in your example, but there may be other ways to do it. Be warned that doing so would make it very difficult to deserialize the data again. – Theo Oct 27 '16 at 15:34
  • can u tell me how to achieve this? – Chinna Rao Oct 27 '16 at 17:15
  • Since your root object has fixed properties like `"id"` and variable properties like `"st1"` and `"st2"`, you could consider the solution from [How to deserialize a child object with dynamic (numeric) key names?](https://stackoverflow.com/questions/40088941/how-to-deserialize-a-child-object-with-dynamic-numeric-key-names). – dbc Oct 27 '16 at 19:10
  • I need to create this type of json String. don't want to deserialize – Chinna Rao Oct 28 '16 at 05:39
  • @ChinnaRao found any solutions ? – King_Fisher Jun 23 '21 at 07:19

0 Answers0