Search code examples
jsonrestsharphubspot

Correct JSON structure using RestSharp


What is the Correct format for sending JSON using RestSharp:

Example PUT JSON:
 {
 "properties": [
{
  "name": "description",
  "value": "A far better description than before"
}
]
}

In C# how to correctly send, I'm attempting with:

     request.AddJsonBody(new
        {
            properties = new[]
            {
                new{property="name",value="about_us"},
                new{property="value",value="My description"}
            }
        });

Below is the full code:

  private void UpdateCompanyProperty(string companyId)
    {

        var hapikey = "{YOUR_HAPI_KEY_HERE}";
        var client = new RestClient("https://api.hubapi.com/");
        var request = new RestRequest("companies/v2/companies/{companyId}", Method.PUT);
        request.AddUrlSegment("companyId", companyId);
        request.AddQueryParameter("hapikey", hapikey);
        request.RequestFormat = DataFormat.Json;

        request.AddJsonBody(new
        {
            properties = new[]
            {
                new{property="name",value="about_us"},
                new{property="value",value="My description"}
            }
        });

        IRestResponse response = client.Execute(request);

        JObject jObject = JObject.Parse(response.Content);
        JToken jvid = jObject["portalId"];

        Debug.WriteLine(jvid);

    }

No errors but not updating or returning values.


Solution

  • Try my answer here:

    https://stackoverflow.com/a/57281157/5478655

    request.RequestFormat = DataFormat.Json; // Important
    
    var input = new Dictionary<string, object>();
    // props could be an array or real objects too of course
    var props = new[]
    {
        new{property="name",value="about_us"},
        new{property="value",value="My description"}
    };
    input.Add("properties", props);
    
    request.AddBody(input);