0

I have an class like this:

[JsonObject(MemberSerialization.OptIn)]
public class Event
{
    [JsonProperty]
    public Guid EventID;

    public string Source;

    public UInt64? EventCode;

    public DateTime? TimeStamp;

    [JsonProperty]
    public string SourceType;

    ...
}

and a web api2 controller like this:

    [HttpPost]
    public IHttpActionResult Post([FromBody]Event @event) { ... }

My problem is that even though all Event parameters are provided in the Post call, the Source, EventCode and TimeStamp are left out. They are left out due to the JsonProperty annotation. But they are in place as the object later is serialized where only the annotated values should be serialized.

So, how do I get all properties deserialized but only some serialized?

galmok
  • 869
  • 10
  • 21
  • you don't want to save the state of data, and then recover. Is that what you want? – Amit Kumar Ghosh Feb 26 '16 at 09:58
  • The webapi receives the event information and decodes a some and passes the event information on, except for a few fields. I could create a new class, EventDTO, and manually copy the fields from Event to EventDTO, but I figured the same class could be used for both. But I can't see how. – galmok Feb 26 '16 at 10:04
  • just don't use the values of these properties in the controller.Allow them to be serialized/deserialized like other properties. – Amit Kumar Ghosh Feb 26 '16 at 10:06
  • The Controller needs the values, but as the object is put in permanent storage, some fields are to be left out. If JSON.NET cannot handle this, I am forced to manually copy all fields to a DTO that only has the required fields. It would be nice if there was an attribute for serialization and for deserialization. – galmok Feb 26 '16 at 10:14
  • use `AutoMapper` instead of mapping manually. http://automapper.org/ – Amit Kumar Ghosh Feb 26 '16 at 10:29

0 Answers0