Mapping JSON data retrieved from WebRequest in ASP.NET 5 using MVC 6

This is my first question, so I apologize if I messed up the formatting or did it wrong at all, do not hesitate to give me pointers, I am always open to study.

Anyway, my problem is that I have a web application that I am working on using ASP.NET 5 and MVC 6, all updated and still for testing, I used localdb and worked with fake data. Now I have a URL with an API token and login information, and I use WebRequest to get the data and stream using StreamReader into a variable by writing it, and then try to return it.

WebRequest req = WebRequest.Create(@"https://url.fortheapi.com/api/search/things?criteria=" + userInput); req.Method = "GET"; req.Headers["username"] = "user"; req.Headers["password"] = "password"; req.Headers["token"] = "token"; StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream()); var responseData = responseReader.ReadToEnd(); Response.WriteAsync(responseData); return View(responseData); 

This is where I am stuck because I don’t know exactly how to pass it to the representation as model data, I don’t have a model at present, and I want to create it based on this database and use Entity Framework to work with it as if I was with localdb. If there is a better way to do this, please feel free to submit it. I will accept all the help that I can get right now.

+5
source share
2 answers

You need to create POCO classes to represent the data you receive from your api call. After receiving the response data, you can simply use javascript serialization to deserialize the response to the object of your POCO class. You can pass this on to your submission.

 public async Task<ActionResult> Contact() { var req = WebRequest.Create(@"yourApiEndpointUrlHere"); var r = await req.GetResponseAsync().ConfigureAwait(false); var responseReader = new StreamReader(r.GetResponseStream()); var responseData = await responseReader.ReadToEndAsync(); var d = Newtonsoft.Json.JsonConvert.DeserializeObject<MyData>(responseData); return View(d); } 

Assuming api returns json data like

 { "Code": "Test", "Name": "TestName" } 

and you created a POCO class called MyData , which can be used to represent the data returned from the api. You can use json2csharp to generate your C # classes from the json response received from your api.

 public class MyData { public string Code { get; set; } public string Name { set;get;} //Add other properties as needed } 

Your look should now be strongly typed for this POCO class.

 @model MyData <h2>@Model.Code</h2> <h2>@Model.Name</h2> 
+2
source

If you get JSON, you can do it differently.

You could wrap the code you posted in a JSON Result action. The following is a very simplified example:

  [HttpPost] public JsonResult GetIncidentId(int customerId, string incidentNumber) { JsonResult jsonResult = null; Incident incident = null; try { incident = dal.GetIncident(customerId, incidentNumber); if (incident != null) jsonResult = Json(new { id = incident.Id }); else jsonResult = Json(new { id = -1 }); } catch (Exception exception) { exception.Log(); } return jsonResult; } 

Calling through Javascript from the view and manually filling out the form (meh).

Or more elegantly, you can create an MVC model to store the received data and serialize JSON in this model. Example below:

From: http://www.newtonsoft.com/json/help/html/deserializeobject.htm

 public class Account { public string Email { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } } string json = @"{ 'Email': ' james@example.com ', 'Active': true, 'CreatedDate': '2013-01-20T00:00:00Z', 'Roles': [ 'User', 'Admin' ] }"; Account account = JsonConvert.DeserializeObject<Account>(json); 

Hope this helps and good luck with your application!

+2
source

Source: https://habr.com/ru/post/1244387/


All Articles