简体   繁体   中英

Convert c# Object to JSON

I need to send a Json to a webservice. Im trying:

var user = new
{
    email = "user@domain.com",
    password = "user1234"
};

var json = JsonConvert.SerializeObject(user);

The result of this serialization is:

{"email":"user@domain.com","password":"user1234"}

But I need to pass the user inside the JSON:

Like this:

{ "user": { "email": "user@domain.com", "password": "user1234" } }

How can I do it?

You need to wrap your object in an object with a user property then:

var user = new
{
    user = new
    {
        email = "user@domain.com",
        password = "user1234"
    }
};

To achieve this you need to create the Classes as below:

public class User
{
    public string email { get; set; }
    public string password { get; set; }
}

public class Root
{
    public User user { get; set; }
}

Create the object of the Root class:

User userInfo = new User();
userInfo.email = "user@domain.com";
userInfo.password = "user1234";

Root userdata = new Root();
userdata.user  = userInfo;

Seralize the data as below:

var json = JsonConvert.SerializeObject(userdata);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM