Search code examples
c#httpwebrequest

Automap HttpWebRequests to a model


HttpWebRequest request = WebRequest.Create("https:...") as HttpWebRequest;
var response = request.GetResponse() as HttpWebResponse;
var reader = new StreamReader(response.GetResponseStream());
var lines = reader.ReadToEnd();

Now lines comes back as

{"username":"me","gender":male}

and I want to auto map this to a model class, that I have set up like this,

public class Person
{
    public string username { get; set; }
    public string gender { get; set; }
}

Any idea of how to go about this ?


Solution

  • You can use Newtonsoft.Json for this task. Just add Newtonsof.Json package to your project and then do:

    var person = JsonConvert.Deserialize<Person>(lines);