Umer Farooq
Umer Farooq

Reputation: 241

Adding Class Name in JSON using 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);

Upvotes: 3

Views: 5433

Answers (4)

kyrylomyr
kyrylomyr

Reputation: 12632

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.

Upvotes: 4

msmolcic
msmolcic

Reputation: 6557

You could use anonymous class to recreate your list and then serialize it if you really want class name as part of your JSON.

var persons = eList.Select(p => new { Person = p }).ToList();
var json = JsonConvert.SerializeObject(persons, Formatting.Indented);

Output:

JSON image

Upvotes: 1

Sreejith
Sreejith

Reputation: 166

Try

var Person = new List<Person>();
Person a = new Person("Umer", 25);
Person b = new Person("Faisal", 24);
Person.Add(a);
Person.Add(b);

var collection = Person;
dynamic collectionWrapper = new {
  myRoot = collection
};

var output = JsonConvert.SerializeObject(collectionWrapper);

Upvotes: 1

TC Alper Tokcan
TC Alper Tokcan

Reputation: 369

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.

Upvotes: 1

Related Questions