Home > OS >  Trying to deserialize Json object passed in body
Trying to deserialize Json object passed in body

Time:10-16

I'm kind of a fresher when it comes to doing API work especially with JSON.

Here's what my code looks like...

Endpoing:

 [HttpPost("postWithBody")]
 public async Task<IActionResult> PostWithBody (string param1, [FromBody] object requestBody)
 {
     
     var x = JsonSerializer.Deserialize<ParamModel>(requestBody); <-- Error cannot convert from 'object' to System.ReadOnlySpan<byte>
       
     return ok(param1); <--this here just so it doesn't bark at me

 }

SO in the above code, I'm erroring out on (RequestBody) with this error:

Error cannot convert from 'object' to System.ReadOnlySpan

 public class ParamModel
 {
       public string PName {get;set;}
       public string PValue {get;set;}
 }

But essentially to finish the demo of what I'm trying to accomplish is, goal is to pass JSON value to this endpoint in the body that looks like this:

{
    "Param1": "XXX",
    "Param2": "111"
}

and my goal would be for CustomParams model class to have the

   PName = Param1
   PValue = "XXX"

and

   PName  = "Param2"
   PValue = "111"

Is this the correct approach I'm taking?

Thank you.

EDIT: I guess I could do something like: [FromBody] ParamModel requestBody

and I did try it, when I pass JSON like this, it came as null in the endpoint:

{"test":"hey"}

But also, I probably would need to do something like this, since I want to have the option of passing multiple params.

 public class ParamList
 {
    public List<ParamModel> data {get;set;}
 }

and have that be [FromBody] ParamList requestBody

CodePudding user response:

First of all I would suggest that you use the model in the action parameter and let the framework do the deserialisation for you:

public async Task<IActionResult> PostWithBody(
    string param1, [FromBody] ParamModel requestBody)
                            

Now you will be able to post JSON in that matches that object, something like this for example:

{ 
    "PName": "test", 
    "PValue": "hey"
}

In your update, you say that you would like instead to use the ParamList object. In that case, you would need JSON that matches, something like this:

{
    "data": [
        { "PName": "test1", "PValue": "hey1" }, 
        { "PName": "test2", "PValue": "hey2" }
    ]
}

Now in your action you can loop over the list like this:

foreach(var param in requestBody.data)
{
    var paramName = param.PName;
    var paramValue = param.PValue;
    // etc.
}
  • Related