Friday, May 22, 2020

C# Properties/Fields and Serialization

I was dealing with an odd dilemma while updating an ASP.Net MVC API. I had created 2 new classes to represent the data the front end was going to POST.

Here's the 2 class definitions in question:

    public class GraphicModel
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string Byline { get; set; }
        public string BylineTitleId { get; set; }
        public string BylineTitleDescription { get; set; }
        public string Category { get; set; }

        public List<GraphicBinary> GraphicBinaries;
    }

and:

    public class GraphicBinary
    {
        public SubmittedImageType ImageType { get; set; }
        public string OriginalFilename { get; set; }
        public string ItemId { get; set; }
        public string RecordId { get; set; }
        public int RecordSequenceNumber { get; set; }
    }

I had set things up on the front end to post the following JSON:

{
    "Title": "AP Poll Stay at Home Protest Approval",
    "Description": "A new UChicago Divinity School/AP-NORC poll finds that two-thirds of Democrats and about half of Republicans disapprove of recent protests of stay at home orders.;",
    "Byline": "F. Strauss",
    "BylineTitleDescription": "STAFF",
    "BylineTitleId": "STF",
    "Category": "a",
    "GraphicBinaries": [
        {
            "ImageType": "PrintGraphicAI",
            "ItemId": "dd142b48fe7c4cc6bf9b42c9c9402e7d",
            "RecordId": "dd142b48fe7c4cc6bf9b42c9c9402e7d",
            "RecordSequenceNumber": 0,
            "OriginalFilename": "ChicagoShootings.ai"
        },
        {
            "ImageType": "PrintGraphicJPEG",
            "ItemId": "ccce25ddc1cb45d898b09eb0d91fcecc",
            "RecordId": "ccce25ddc1cb45d898b09eb0d91fcecc",
            "RecordSequenceNumber": 0,
            "OriginalFilename": "ChicagoShootings.jpg"
        }
    ]
}

Here's the signature on my controller method:

    [HttpPost]
    public JsonResult Graphic(PhotoAction actionType, bool hid, GraphicSubmission graphicModel)

What was happening is the method was invoked properly but the GraphicBinaries field was always empty even though the JSON was correct. 

I posted a question on Stack Overflow (greatest site on earth!) here:


The long and short of it is there's a difference between fields and properties in C# as noted here:


This is critical because only properties are serialized/deserialized and the GraphicBinaries field was a field not a property!

No comments:

Post a Comment