如何将对象序列化为Json,并将对象类的名称作为根添加到桌面c#应用程序中?

时间:2021-08-27 04:44:38

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:

当我试图将这个对象作为Json发送到web服务器时,使用以下代码:

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

this is the json that is sent:

这是发送的json:

{name:"John"}

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

我想插入一个根节点。Json应该是这样的:

{user:{name:"John"}

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

我找到了一个解决方案,但它只适用于web应用程序。对桌面应用程序有什么想法吗?

1 个解决方案

#1


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 });

#1


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 });