Search code examples
c#.netjsonconvert

Get JSON string as object at server side and deserialize it


I have a method at a controller which takes an object, And i need to deserialize differently depending on how i create the service at DI. The method is bool SetSnmpRequest(Object obj);

Then in the controller

public IActionResult Set([FromBody]object details)
    {
        bool setSuccesses = _devicesManager.SetSnmpRequest(details);

        if (setSuccesses)
            return Ok();

        return BadRequest();
    }

This is the JSON passed from the client {"Name":"Power" ,"Value":"MED","ChannelIndex":"1"}

And the object i`m trying to deserialize to

public class SetRequestModel
        {
            public string Name { get; set; }
            public string Value { get; set; }
            public int ChannelIndex { get; set; } = 0;
        }

The desirialization SetRequestModel details = JsonConvert.DeserializeObject<SetRequestModel>((string)obj);

The problem at all that is that JsonConvert.DeserializeObject takes a string and i get an exception when casting the object to a string

System.InvalidCastException: Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.String'.

Solution

  • Just let your middleware do its thing for you.

    public IActionResult Set([FromBody]SetRequestModel details)
    {
        ...
    }
    

    If you really want to take in the generic object, you will first need to serialize it, then deserialize it. This is because it is passed into your action method as an anonymous object, not a string. But using your typed models in the action signature is considered a better practice.

    Check out this official tutorial: Create a Web API with ASP.Net Core