Adrian S
Adrian S

Reputation: 544

.Net Core: controlling Json generated by Controller.Json method

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

Answers (2)

David Pine
David Pine

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.

  1. Use the JsonIgnore attribute and mark the properties you want omitted.
  2. Have your 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

Ali
Ali

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

Related Questions