Search code examples
c#jsonasp.net-mvcrestsharp

How to send JSON with dynamic properties using RestSharp?


I want to create a JSON object that has one dynamic property to send a request to an external API. Example:

{
    "prop1": "val1",
    "prop2": "val2",
    "prop3": {
        "dynamic_prop": "val"
    }
}

This is the only code that gets me a valid response:

var request = new RestRequest(url, Method.PUT);
request.AddHeader("content-type", "application/json");

var body = new
{
    prop1 = "val1",
    prop2 = "val2",
    prop3 = new { dynamic_prop = "val" }
};

request.AddJsonBody(body);

However, in this case dynamic_prop isn't dynamic. And as I've read anonymous types can't have dynamic props.

I tried using JObject:

var jobject = JObject.Parse("{\"dynamic_prop\":\"val\"}");
var body = new
{
    prop1 = "val1",
    prop2 = "val2",
    prop3 = jobject
};

However the JObject isn't serialized properly, I get [[[]]], I'm guessing because that object has numerous other properties (First, ChildrenTokens etc), same goes for JToken. I also tried with ExpandoObject and couldn't get it to work.


Solution

  • JObject gets serialized as [[[]]] because RestSharp's serializer treats it as IEnumerable instead of as a dictionary.

    But you don't need to use JObject here; just use a Dictionary<string, string> to create your dynamic property:

    var dict = new Dictionary<string, string>();
    dict.Add("dynamic_prop", "val");
    var body = new
    {
        prop1 = "val1",
        prop2 = "val2",
        prop3 = dict
    };