Need rules/doc for casting JSON to c# class

59 Views Asked by At

I am trying to trouble shoot an angular controller calling c# webApi2 project.

I do not think I fully understand how c# goes about casting JSON to a type.

I often get null in the webform_ variable

 [System.Web.Http.HttpPatch]
        [Route("{itemId_}")]
        public IHttpActionResult PatchItemById([FromUri] int itemId_, [FromBody] parent webForm_)
  

  

I can certainly make the value be NULL if I pass in mal formed JSON. That makes sense.

It seems like c# does a good job of 'making the json fit the expected class' Take this JSON

{ "name":"test",
  "children":  [{
            "nm": "child1",
            "v1": "NM",
            "v2": "12000000",
            "v3":  546
        }]
 }

And these classes

 public class parent {
          public string name;
          public sillyObject[]   children;
    } 

    public class mSillyObject
        {
            public string nm;
            public string v1;
            public string v2;
            public string r;
            public string a;
    
        }

This seems to work even though the JSON has elements where are not in the class, and vice versa. The resulting object has all the fields filled in as best as possible

However , at other times, I am getting webform = null_ even though JSONLint tells me I am sending in valid JSON.

I have googled everyway I can think of.
There must be some doc somewhere that explains this? Can anyone suggest some documentation links , or offer some thoughts on trouble shooting and common mistakes.

tyia greg

2

There are 2 best solutions below

0
On BEST ANSWER

you can try this for your json, replace mproject by parent class, make itemId_ optional and remove HttpPath

[Route("{itemId_?}")]
public IHttpActionResult PatchItemById([FromUri] int itemId_, [FromBody] parent webForm_)
0
On

would still be very interested in reading about how this works.

i have been able to determine these rules

  • the json can have properties that the model does not have
  • the model can have properties that are not in the json

if the model has public string property1 and the json has "property1" : [] the cast will fail. It doesnt seem to matter if the array has contents or not. C# is looking for a single item, not an array.

if the model has public sillyObject silly;

  • having the property missing from the JSON works
  • having "silly" : null works
  • having "silly" : {} causes the cast to fail

ill post more gotchas here if i come across any... or if i find an article describing this