Search code examples
c#jsonhttp-postrestsharpwebapi

Nested Object in Json Post request


I need to create a post request that looks like the following, with a nested object within the request. I am not sure how to add the "Person": section to the request itself. I've tried different things and now I think i am completely over thinking it. Here's what I need:

{
"LocationId": 76349
"Date": 07/05/2020
"AppointmentType": "Xray / Casting"
"Person":{
"Lastname":"Smith","Firstname":"John","Gender":"M","Age":26}
} 

And here's the last thing I've tried.  This fails with "Unable to determine Json object type for type Person

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RestSharp;
using System.IO;
using Newtonsoft.Json.Linq;
using Json.Net;


public class Person
    {
     
        public string Lastname { get; set; }
        public string Firstname { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }
    }

    JObject jObjectbody = new JObject();
            jObjectbody.Add"LocationId", 76349);
            jObjectbody.Add("Date", 07/05/2020);
            jObjectbody.Add"AppointmentType", "Xray / Casting");
    jObjectbody.Add(new Patient
            {
                Lastname = "Smith",
                Firstname = "John",
                Gender = "M",
                Age = 26        
            });    

Am I going about this all wrong? Is there a better way to do it?


Solution

  • You dont need to create a json, you can simply pass the object like this.

    Client.PostAsJsonAsync(url, obj);
    

    Its in Microsoft.AspNet.WebApi.Client nuget package