My controller method is as follows
public ActionResult Index()
{
Tweets model = null;
var client = new HttpClient();
var task = client.GetAsync("http://localhost:33615/api/product").ContinueWith((t) =>
{
var response = t.Result;
var readtask = response.Content.ReadAsAsync<Tweets>();
readtask.Wait();
model = readtask.Result;
});
task.Wait();
return View(model.Result);
}
The url return the row as follws:
[{"Id":1,"Name":"Honda Civic","Description":"Luxury Model 2013"},{"Id":2,"Name":"Honda Accord","Description":"Deluxe Model 2012"},{"Id":3,"Name":"BMW V6","Description":"V6 Engine Luxury 2013"},{"Id":4,"Name":"Audi A8","Description":"V8 Engine 2013"},{"Id":5,"Name":"Mercedes M3","Description":"Basic Model 2013"}]
My Tweets and tweet class are as follows:
public class Tweets
{
public Tweet[] Result;
}
public class Tweet
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
}
I can't figure it out where i do mistake.it gives me following error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RestFiddlerTest.Controllers.Tweets' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly
How to fix this.
I've double checked your code and there are a few issues with it.
First of all, I don't see your logic to deserialize to Json, according to the JSon object, I'm guessing that you're using Newtonsoft.Json?
Then you have a class Tweets which contains an array of Tweet objects.
Now, when you create a small sample, like the following:
var dataToSerialize = new Tweets();
dataToSerialize.Result = new [] { new Tweet { Description = "Desc", Name = "Name" } };
var data = JsonConvert.SerializeObject(dataToSerialize);
The output of this piece of code will be the following:
{"Result":[{"Id":null,"Name":"Name","Description":"Desc"}]}
This is not the same as the output you get from your WebAPI.
Now, when you do use Newtonsoft.Json, when serializing your object, you are probably doing something like this:
const string JSon = "[{\"Id\":1,\"Name\":\"Honda Civic\",\"Description\":\"Luxury Model 2013\"},{\"Id\":2,\"Name\":\"Honda Accord\",\"Description\":\"Deluxe Model 2012\"},{\"Id\":3,\"Name\":\"BMW V6\",\"Description\":\"V6 Engine Luxury 2013\"},{\"Id\":4,\"Name\":\"Audi A8\",\"Description\":\"V8 Engine 2013\"},{\"Id\":5,\"Name\":\"Mercedes M3\",\"Description\":\"Basic Model 2013\"}]";
var data = JsonConvert.DeserializeObject<Tweets>(JSon);
Note: I've put the Json string in a string because I didn't have the time to write a full WebAPI.
Now, this will not work, because the string I input and that's also the one that your controller does return is not a Tweets object (remember you're missing the Result in your JSon string? Instead, this is a array of Tweet objects, so you can change your code like the following:
var data = JsonConvert.DeserializeObject<Tweet>(JSon);
Unfortunately, you will receive the exact same error. So why is that? Because you're trying to deserialize your object into an object of type Tweet while your object is an array of type Tweet.
So, modify your code like the following:
var data = JsonConvert.DeserializeObject<Tweet[]>(JSon);
Now, you're deserializing your object into the correct type.
So, I do hope that this post will help you.
Kind regards,
I used Newtonsoft.Json.
public ActionResult Index()
{
List<Tweet> model = null;
var client = new HttpClient();
var task = client.GetAsync("http://localhost:33615/api/product").ContinueWith((t) =>
{
var response = t.Result;
var readtask = response.Content.ReadAsAsync<List<Tweet>>();
readtask.Wait();
model = readtask.Result;
});
task.Wait();
return View(model);
}
Related
I am trying to deserialize the Json to List object of Student which conister of studentName and studentId. I do get the jsonResponse with around 200 students but when I get to deserialize I got the below error. I did reserch for this error and the fix for the issue is similar to the code that I have so I am not sure what is wrong.
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyApp.Models.Student]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
public static async Task<List<Student>> GetUserInfo()
{
var token = await AccessToken.GetGraphAccessToken();
// Construct the query
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Globals.MicrosoftGraphUsersApi);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
// Ensure a successful response
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
// Populate the data store with the first page of groups
string jsonResponse = await response.Content.ReadAsStringAsync();
var students = JsonConvert.DeserializeObject<List<Student>>(jsonResponse);
return students;
}
Below is the JSON response from Microsoft Graph Api
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(studentName,studentId)",
"value": [
{"studentName":"Radha,NoMore","studentId":"420"},
{"studentName":"Victoria, TooMuch","studentId":"302"}
]
}
C# student Class:
public class Student
{
public string studentName { get; set; }
public string studentId { get; set; }
}
The JSON response contains a value: property, and that property contains the students as array data. Therefore you'll need to make an additional class that has a List<Student> value property, deserialize to that class, and then you can use the List of Students that is in the value property, as follows:
var listHolder = JsonConvert.DeserializeObject<StudentListHolder>(jsonResponse);
var list = listHolder.value;
foreach (var student in list)
{
Console.WriteLine(student.studentId + " -> " + student.studentName);
}
This is the additional class:
public class StudentListHolder // pick any name that makes sense to you
{
public List<Student> value { get; set; }
}
Working demo (.NET Fiddle): https://dotnetfiddle.net/Lit6Er
I have created small class
class JsonResponse
{
public string Response { get; set; }
}
Then in my program I send some json data and wait store reply to the following variable
var ResultJSON = Post(uri, values);
while parsing I get
Service Error: Cannot convert object of type 'System.String' to type
'App.someclass+JsonResponse'
using Newtonsoft.Json;
class JsonResponse
{
public string Response { get; set; }
}
class Utility
{
public JsonResponse JsonDeserialisation(string response)
{
TextReader textReader = new StreamReader(response);
JsonTextReader jsonReader = new JsonTextReader(textReader);
return JsonSerializer.CreateDefault().Deserialize<JsonResponse>(jsonReader);
}
}
class Main
{
static void Program()
{
var ResultJSON = "Json String received from post";//Post(uri, values);
var deserialisedJson = Utility.JsonDeserialisation(ResultJSON);
}
}
Add newtonSoft.json nuget package to project
try
var Result = new JavaScriptSerializer().Deserialize<JsonResponse>(ResultJSON.**Response**);
looks to me that you are trying to deserialize from an object rather than the string response
Try this, may give your JSON file to result variable.
var result = Convert.ToString(ResultJSON);
Try using using newtonsoft.json downloadable here or use the nuget package.
It has a function that does exactly what you want. Expecting the result of the Post is in string format of course.
var result = JsonConvert.DeserializeObject<JsonResponse>(ResultJSON);
Your JsonResponse class must look exacly the same as the json your getting. So make sure if you get more data in the json that you want to save in the class the names are the same.
If you have anymore questions feel free to ask.
I need to call this method in MVC controller and pass the UpdateRequest object as json format. how I can do that?
[HttpPost]
[Route("updatecertificate")]
public void updatecertificate([FromBody] UpdateRequest certificatereviewed)
{
loansRepository.updatecertificate(certificatereviewed.Id, certificatereviewed.CertificateReview);
}
and this is the input class:
public class UpdateRequest {
public int Id { get; set; }
public bool CertificateReview { get; set;}
}
this is how I call and send separate variable but now I like to send the class object in json format.
private async Task UpdateFundingCertificateReviewed(int id, bool fundingCertificateReviewed)
{
await httpClient.PostAsync(string.Format("{0}/{1}", LoanApiBaseUrlValue, updatecertificate),null);
}
I personally like Newtonsoft.Json to serialize the object.
private async Task UpdateFundingCertificateReviewed
(int id, bool fundingCertificateReviewed)
{
using (var client = new HttpClient())
{
var url = string.Format("{0}/{1}", LoanApiBaseUrlValue, updatecertificate);
var updateRequest = new UpdateRequest { Id = 1, CertificateReview = true};
var data = JsonConvert.SerializeObject(updateRequest);
await client.PostAsync(url, data);
}
}
FYI: Async without return is not a good practice. However, it is out of the original question.
If you want to transform an object into a JSON string, see this question: Turn C# object into a JSON string in .NET 4
var json = new JavaScriptSerializer().Serialize(obj);
Is this what you are after or do you want to know how to construct the http request with a JSON object in the body?
your questionis not very clear, what is the outcome that you expect ?
If you want to POST an request with JSON body you can check the #Win comment,
however if you want to make an Response from the Api to the MVC project you should do a bit more steps tough. :))
this is my first question, so I apologize if I mess up the formatting or do this wrong in general, feel free to give me pointers, I'm always open to learn.
Anyway, my issue at hand is that I have a web application I'm working on using ASP.NET 5 and MVC 6, all up to date, and so far for testing, I've been using the localdb and working with fake data. Now, I have a url, with an API token, and login info, and I am using a WebRequest to get the data and stream it with a StreamReader into a variable, writing it, and then trying 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);
Here is where I'm stuck because I am not sure exactly how to pass it to the view as model data, I have no model currently, and I want to make one based on this database and use Entity Framework to work with it like I have been with the localdb. If there's a better way to do it, please feel free to present it. I will accept all the help I can get right now.
You need to create POCO classes to represent the data you receive from your api call. Once you get the response data, you may simply use a javascript serialize to deserialize the response to an object of your POCO class. You can pass this to your view.
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 your api returns json data like this
{ "Code": "Test", "Name": "TestName" }
and you have created a POCO class called MyData which can be used to represent the data coming back from the api. You may use json2csharp to generate your C# classes from the json response you received from your api.
public class MyData
{
public string Code { get; set; }
public string Name { set;get;}
//Add other properties as needed
}
Now your view should be strongly typed to this POCO class
#model MyData
<h2>#Model.Code</h2>
<h2>#Model.Name</h2>
If what you are receiving is JSON, you can accomplish this is many ways.
One would be to wrap the code you've posted into a JSON Result typed Action. A very simplistic example below:
[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 it via Javascript from the view and manually populating your form (meh).
Or more elegantly, you could create an MVC model to hold the data you receive and serialise the JSON into that model. An example of which is 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 app!
I get the following JSON that I am trying to convert to a business object using RestSharp
{
"valid":true,
"data":[
{
"dealerId":"4373",
"branchId":"4373",
}
]
}
I wish to convert to:
public class Dealer
{
public string dealerId ;
public string branchId;
}
But this fails, though the JSON is fine:
var client = new RestClient("http://www.????.com.au");
var request = new RestRequest(string.Format("service/autocomplete/dealer/{0}/{1}.json", suburb.PostCode, suburb.City.Trim().Replace(" ", "%20")), Method.GET);
var response2 = client.Execute<Dealer>(request);
return response2.Data;
Your business object doesn't match the response JSON you are getting back. If you want your response to serialize, your C# object would look something like
public class DealerResponse
{
public bool valid { get;set; }
List<Dealer> data { get;set; }
}
public class Dealer
{
public string dealerId;
public string branchId;
}
I haven't tested this code, but even though you are only interested in the information in 'data', your response C# objects still need to represent the whole JSON response to serialize correctly.
Hope that helps.