Home > database >  Deserialize objetc into own type in c#
Deserialize objetc into own type in c#

Time:09-13

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?

Thanks in advice

CodePudding user response:

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

CodePudding user response:

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

The you Deserialize an Object like this: Please have a look at this https://www.newtonsoft.com/json/help/html/SerializingJSON.htm

var user = JsonConvert.DeserializeObject<User>(json);
  • Related