How do I skip out certain properties when converting my object to json through the controller’s method?
public JsonResult GetPerson(int PersonId)
{
Person thisPerson = Person.GetById(PersonId);
return Json(thisPerson); //Please strip SecretAlterEgoName from your results please!
}
class Person
{
int PersonId { get; set; }
string Name { get; set; }
string SecretAlterEgoName { get; set; } //Must not send this! No on must know!
}
And I want to avoid this:
{“PersonId”:3,”Name”:”Peter Parker”,”SecretAlterEgoName”:”Spiderman”}
and instead show this:
{“PersonId”:3,”Name”:”Peter Parker”}
I was hoping to avoid having to use StringBuilder to generate my json string, and avoid creating a new object with less properties to transfer to.
I’m reasonably sure — but can’t test right now — that you can generate the JSON from an anonymous type, and only include the fields that you’re interested in when you create the type: