Pergunta

I can't really find a working example, maybe it is because its simply not possible?

I'd like to take a C# anonymous type object like the following:

var postBody = new
{
   friend = new 
   {
      name = "dave",
      last ="franz"
   },
   id = "12345",
   login = "mylogin" 
};

and post it to my web service in a simple http POST with the following post body:

{
   "friend" :
   {
      "name" : "dave",
      "last" : "franz"
   },
   "id" : "12345",
   "login" : "mylogin" 
};
Foi útil?

Solução

Pretty easy using Json.net. You can get it using the nuget package manager in VS.

var postBody = new
{
   friend = new 
   {
      name = "dave",
      last ="franz"
   },
   id = "12345",
   login = "mylogin" 
};
var postString = Newtonsoft.Json.JsonConvert.SerializeObject(postBody);
using(var wc = new WebClient())
{
    wc.Headers.Add("Content-Type", "application/json");
    var responseString = wc.UploadString(serviceAddress, "POST", postString);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top