Pass two JSON object by web client post method C#

爱⌒轻易说出口 提交于 2019-12-05 18:31:57

You can create POCO classes for the Requestor, Company like follows and use JSON.net to do the conversion for you.

public class Company
{
    public string Id { get; set; }
    // Other properties
}

public class Requestor
{
    public string Id { get; set; }

    public string Email { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
    // Other properties
}

public class Container
{
    public Company Company { get; set; }

    public Requestor Requestor { get; set; }
}

var requestor = new Container();
requestor.Company = new Company { Id = "sampleid" };
requestor.Requestor = new Requestor
{
    FirstName = "test",
    LastName = "testname"
};

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var data = JsonConvert.SerializeObject(requestor, settings);

WebClient client = new WebClient();
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
// Code for the credentials etc
client.UploadString(@"your url", data);

Hope this helps. For this to work, you need to have a reference to JSON.net. Since you are using .net 4.5 with Web API, you should be having the reference already.

You get invalid parameter error because square bracket are not allowed in a url. If you want use characters that are not include in RFC 1738 you must use HttpUtility.UrlEncode("String")(msdn reference)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!