How do you turn a list of Objects into a JSON String?
The code below returns only one attribute, People. How to add multiple attributes to it? I have been using JsonConvert to change an object into JSON format. I would be open other options / opinions on how to do it. Any help would be much appriciated!
Wanted Response:
{"People":
{"Person":
{"FirstName":"Mike", "LastName":"Smith", "Age":"26"}
},
{"Person":
{"FirstName":"Josh", "LastName":"Doe", "Age":"46"}
},
{"Person":
{"FirstName":"Adam", "LastName":"Fields", "Age":"36"}
}
}
The Person Class
public class Person
{
public string FirstName { get ;set; }
public string LastName { get ;set; }
public int Age { get ;set; }
}
Processing Logic
public JsonResult GetAllPeople()
{
List<Person> PersonList = new List<Person>();
String responseJSON = "";
foreach(string data in something){
//Some code to get data
Person p = new Person();
p.FirstName = data.FirstName ;
p.LastName = data.LastName
p.Age = data.Age;
responseJSON += new { Person = JsonConvert.SerializeObject(p) };
}
return Json(new { People = JsonConvert.SerializeObject(responseJSON ) }, JsonRequestBehavior.AllowGet);
}
Create a list of objects.
will return
you need add a class, we will name it
People
this shall return exactly what you want
The
will actually serialize the object it takes as a parameter. As you are passing in a json string, it's getting double encoded. Create an anonymous object with a property named People, then serialize it. so you can:
or