Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deserialize objetc into own type in c#

I am new to c# and I am willing to convert a Object into a class representing a User. I am retrieving the object from a http request to an API. My code is:

 private async void getUser()
        {
            var requestURI = new HttpRequestMessage();
            string url = "https:...";
            requestURI.RequestUri = new Uri(url);
            requestURI.Method = HttpMethod.Get;
            requestURI.Headers.Add("Accept", "application/json");
            HttpResponseMessage responseURI = await client.SendAsync(requestURI);
            if (responseURI.StatusCode == HttpStatusCode.OK)
            {
                Debug.WriteLine("Get User OK");
                var UserString = await responseURI.Content.ReadAsStringAsync();
                Debug.WriteLine("User: " + UserString);
                var UsersJson = JsonConvert.DeserializeObject(UsersString);
                Debug.WriteLine(UserJson);
            }
            else
            {
                Debug.WriteLine("User GET request failed");
            }
        }

The output is:

{
  "Username": "Alice",
  "IP": "192.13.2.2",
  "Levels": "1,2"
}

How do I create a class or a type to later deserealize this object into it? When the type/class is created, how do I deserealize the object into it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advice

>Solution :

You can use this website – https://json2csharp.com/ – to generate the C# classes.

In this case, the class would be as follows:

public class User
{
    public string Username { get; set; }
    public string IP { get; set; }
    public string Levels { get; set; }
}

For deserialization to this class, you can use as follows:

var user = JsonConvert.DeserializeObject<User>(UsersString);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading