0

I am building a web api method in c# which should be capable of accepting string value or Complex type like Objects. For that i have written below sample snippet which seems to be working with Content-Type: 'application/json'.

public IHttpActionResult jsonstring([FromBody] dynamic json)
{
    string type = Convert.ToString(HttpContext.Current.Request.Headers["type"]);
    if (type == "json")
    {
        List<CDump> jsondump = json.ToObject<List<CDump>>();
    }
    else if (type == "string")
    {
        //Decompress json string
        List<CDump> jsondump = JsonConvert.DeserializeObject<List<CDump>>(json);
    }
    else if (type == "pipe")
    {
        //string str = File.ReadAllText(@"C:\Users\RJhaveri\Desktop\1t-c300420.txt");
        string[] alllines = json.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
    }
    return Ok();
} 

To get any type of data whether complex objects or string type of data, i am using dynamic keyword. What i wonder is, will i have any impact in implementing or making request to this api?

Thanks in advance!

Ronak
  • 187
  • 2
  • 17
  • `dynamic` is extremely inefficient. Try `object` instead or `JRaw`. – ckuri Feb 10 '21 at 17:57
  • Can you please brief? I mean how to use object or JRaw. – Ronak Feb 11 '21 at 09:15
  • 1
    Instead of `dynamic json` write `object json`. If the body is a JSON primitive (e.g. a bool, a number or a string surrounded by quotes) `json` would be of type bool, int or string. If the body is a JSON object (i.e. something like {...}) `json` would be of type JObject, and if the body is a JSON array (i.e. [...]) `json` would be of type JArray. As you expect an array/list `jsondump` would then be `List jsondump = ((JArray)json).ToObject>();`. – ckuri Feb 11 '21 at 20:33

0 Answers0