2

Supposing I have this object:

 var user = new User() { name = "John" };

When I am trying to send this object as Json to an web server using this code:

 HttpResponseMessage response = await client.PostAsJsonAsync(url, user);

this is the json that is sent:

{name:"John"}

I would want to insert a root node. The Json should look like this:

{user:{name:"John"}

I found a solution, but it was only for web apps. Any ideas for desktop apps?

1 Answers1

1

Use an anonymous object to wrap up your user object e.g.

var userObj = new User() { name = "John" };
client.PostAsJsonAsync(url, new { user = userObj });
James
  • 80,725
  • 18
  • 167
  • 237
  • James it seams that your method is working. But still is not the best because every time I call the method I have to specify the name of the root which is a disadvantage that will affect my work. Do you have any other idea? – Stefan Razvan Florea May 24 '14 at 19:19
  • @RazvanFlorea Well you could create a wrapper class if you'd prefer but I'd say you aren't really gaining much. Why would this code present such a big issue? – James May 24 '14 at 19:45
  • For example if I want to make a method that takes as arguments the object to be sent and the url (method that will be called for sending different objects), then, probably, I have to come with one more argument which will be the name of the root, which does not seem to be very elegant. I was thinking about a solution that is taking advantage of the object that is sent. Here you can see a solution for ASP.NET apps: http://stackoverflow.com/questions/16294963/json-net-serialize-object-with-root-name – Stefan Razvan Florea May 24 '14 at 20:24