Search code examples
c#jsonasp.net-web-apijson-deserialization

Receiving the key value pair as input parameter


I am trying to receive the below key value pair as the input parameter to my Web API

json=%7B%0A%22MouseSampleBarcode%22%20%3A%20%22MOS81%22%0A%7D%0A

where the right of the string is the URL encoded JSON which looks like

{
"MouseSampleBarcode" : "MOS81"
}

How can I parse this and store them in to the Model class

 [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
 {
  string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();

where the CoreBarCodeDTO looks like below

public class CoreBarCodeDTO
{
    public class RootObject
    {
        public string MouseSampleBarcode { get; set; }
    }
 }

Solution

  • You could do it this way. Change your class to this definition. In your controller coreBarCode.json will have the the json which you can then work with as needed:

    public class CoreBarCodeDTO
    {
        private string _json;
        public string json { get { return _json; }
            set {
                string decoded = HttpUtility.UrlDecode(value);
                _json = decoded;
            }
        }
    }
    

    Update

     [HttpPost]
     public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTOcoreBarCode coreBarCode)
     {
        string Bar_Code = coreBarCode.json;
        //work with the JSON here, with Newtonsoft for example
        var obj = JObject.Parse(Bar_Code);
        // obj["MouseSampleBarcode"] now = "MOS81"
    
     }