Home > Blockchain >  Need rules/doc for casting JSON to c# class
Need rules/doc for casting JSON to c# class

Time:05-22

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

CodePudding user response:

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_)

CodePudding user response:

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 property1 as a string, and the json has an array as the value for that property. it will error and there will be no useful error message.

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

  • Related