Your answer probably fits your console application as JSON (the reason your browser gets it as XML, due to the different Accept headers, you can find out about this if you look at Content Consolidation ). So what you need to do is parse the JSON and deserialize it into your object. There are so many libraries that can do this for you.
First, make sure your MyClass defined in the class library project, which references your web API project and your console project. This allows us to reuse the class definition without having to have a separate copy in both projects.
Next, you need a JSON parsing library. There is one built in to .NET, but there is a third-party one called Json.NET , which is the gold standard. My answer will use it, since I am more familiar with it. Install the Newtonsoft.Json package in the console application.
Then modify the console application as follows:
using Newtonsoft.Json; // at the top of your file static void Main(string[] args) { var cts = new CancellationTokenSource(); MainAsync(args, cts.Token).Wait(); } static async Task MainAsync(string[] args, CancellationToken token) { string baseAddress = "http://localhost:18207/api/values/GetMyClass"; using (var httpClient = new HttpClient()) { string json = await httpClient.GetStringAsync(baseAddress); MyClass instance = JsonConvert.DeserializeObject<MyClass>(json); } }
The JsonConvert class handles JSON serialization and deserialization. When deserializing, we just say which class we are deserializing to, and it will try to convert the JSON into an instance of that class and return it.
mason source share