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);
1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

He's not asking about deserialisation, from what I gather he wants the root of the json to start with the word Person
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);

1 Comment

in the line var collection = Person, did you mean to instead type "Person", ie a string?
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

2 Comments

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.
@AmithGeorge You're absolutely right. I edited my answer, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.