0

I am currently developing a ASP.NET WebAPI using JSON.NET. I am looking to reduce traffic and want to ignore certain properties of my models for serialization, i.e. I don't want to return them in my JSON response, but I want to accept them when they are passed to my endpoint.

Example class

public class User {

    public int Id { get; set; }
    public string Name { get; set; }
    public string Role { get; set; }

}

Use-cases

  • I've got a POST endpoint that takes a User model as a parameter. The request contains Name and Role. Those props should be parsed into my User.
  • I've got a GET endpoint that returns a User. I only want the response to contain Id and Name. Role should be ignored.

Problem

When I use the JsonIgnore attribute from JSON.NET, the property is ignored entirely. It is not serialized for my response, but the prop of my User is null, when I post the JSON User to my endpoint.

Is there a way to ignore a prop only for serialization?

Thank you in advance!

2
  • I believe you may have to separate your Input / Output models Commented May 2, 2016 at 19:02
  • I thought about that, but want to avoid it, if possible. Commented May 2, 2016 at 19:03

2 Answers 2

2

That's exactly what Data Transfer Objects are for. You should create different DTOs for different purposes (GET/POST).

Sign up to request clarification or add additional context in comments.

4 Comments

Let's say I want to add a user. I would have a UserDTO that is send to my endpoint. I create the user in the database and get back my user object containing the id. To get that created user info to the frontend, I would convert that user model to another user DTO, is that correct or what would be best practice?
yep, that's the way to go.
Sounds like you need a good project structure to avoid getting confused with all the models/DTOs. Thanks for your answer!
Absolutely. DTOs are made right for that purpose: when you cross layers/tiers boundaries you need DTOs to exchange data. If you wouldn't distinguish them then imagine if you want to add something more tomorrow into GET view of the entity? It would create huge mess. (that's just one example)
0

Use this and pass null when you want to ignore it!

[JsonProperty("property_name", NullValueHandling=NullValueHandling.Ignore)]

Comments

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.