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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With