3

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);
Umer Farooq
  • 221
  • 1
  • 4
  • 14

4 Answers4

4

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.

kyrylomyr
  • 12,192
  • 8
  • 52
  • 79
1

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.

Community
  • 1
  • 1
TC Alper Tokcan
  • 369
  • 1
  • 13
1

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

msmolcic
  • 6,407
  • 8
  • 32
  • 56
  • Wouldn't just `eList.Select(p => new { Person = p })` suffice? We know that each person object is serialized properly. We just need to key each object to the string "Person". Please correct me if I missed something. – Amith George Jul 04 '15 at 12:16
  • @AmithGeorge You're absolutely right. I edited my answer, thanks. – msmolcic Jul 04 '15 at 12:23
1

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);
Amith George
  • 5,806
  • 2
  • 35
  • 53
Sreejith
  • 166
  • 8