Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Class Name in JSON using C#

Tags:

json

c#

I created below JSON of Person class using JSON.NET But "Person" is not showing up anywhere in JSON. I think it should show up in the start. What is the problem or how to resolve? Thank you.

[
  {
    "Name": "Umer",
    "Age": 25
  },
  {
    "Name": "Faisal",
    "Age": 24
  }
]

C# code is here which generated JSON

List<Person> eList = new List<Person>();
Person a = new Person("Umer",25);
Person b = new Person("Faisal", 24);
eList.Add(a);
eList.Add(b);
string jsonString = JsonConvert.SerializeObject(eList,Formatting.Indented);
like image 472
Umer Farooq Avatar asked Feb 18 '26 23:02

Umer Farooq


2 Answers

You need to add a TypeNameHandling setting:

List<Person> eList = new List<Person>();
Person a = new Person("Umer", 25);
Person b = new Person("Faisal", 24);
eList.Add(a);
eList.Add(b);
string jsonString = JsonConvert.SerializeObject(eList, Formatting.Indented,
    new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });

This way each JSON object will have an additional field "$type":

[
    {
        "$type" : "YourAssembly.Person"
        "Name" : "Umer",
        "Age" : 25
    },
    ...
]

For more details see the documentation.

like image 96
kyrylomyr Avatar answered Feb 20 '26 13:02

kyrylomyr


There is no problem in that.It can be deserialized that way.

You can deserialize it like that :

Person deserialized = (Person)JsonConvert.DeserializeObject( serializedText ,typeof(Person))

But if you need the root this question may help.

like image 23
TC Alper Tokcan Avatar answered Feb 20 '26 13:02

TC Alper Tokcan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!