Reputation: 544
By default, Controller.Json generates JSON for each public member of a class. How can I change this so that some members are ignored. Please note that I am using .Net Core.
Example:
[HttpGet("/api/episodes")]
public IActionResult GetEpisodes()
{
var episodes = _podcastProvider.Get();
return Json(episodes);
}
Thanks.
Upvotes: 3
Views: 6425
Reputation: 24535
How can I change this so that some members are ignored?
Under the covers this uses Newtonsoft.Json
. There are two ways you can do this.
JsonIgnore
attribute and mark the properties you want omitted.episodes
class define itself as "opt-in", meaning only properties marked with JsonProperty
are serialized. [JsonObject(MemberSerialization.OptIn)]
It depends on the number of properties you need omitted versus serialized.
public class Episode
{
public int Id { get; }
[JsonIgnore] public string Name { get; }
[JsonIgnore] public Uri Uri { get; }
[JsonIgnore] public long Length { get; }
}
The above will yield the same JSON as this:
[JsonObject(MemberSerialization.OptIn)]
public class Episode
{
[JsonProperty]
public int Id { get; }
public string Name { get; }
public Uri Uri { get; }
public long Length { get; }
}
Upvotes: 3
Reputation: 1085
You can use [JsonIgnore]
attribute that available in Newtonsoft.Json
namespace like below:
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
public int Age { get; set; }
}
Upvotes: 7