3

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.

1
  • 1
    You shouldn't do that for two reasons: a) it tightly couples your API to the Database models (each change to it breaks your API) and b) it tightly couples your viewmodels to JSON.NET. You should always use own models for returning API values (i.e. viewmodels, binding models, DataTransferObjects) Commented Oct 11, 2016 at 11:57

2 Answers 2

7

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

3

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; }
}

2 Comments

Thank you. I didn't realise Newtonsoft.Json was included in .Net core.
You are welcome. Also, it is noteworthy to mention that there is a actually an overload too for the Json method, that takes the SerializationSettings instance. Which allows for even more control.

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.