Access JSON values from URL - c#

I am trying to get data from a URL that contains JSON values. These values are to be used in my windows 8 desktop app. The code I have tried is seen below.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(App.DataServiceUrl + "/productcategory");
var Groups = new List<GroupList>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var prods = JsonConvert.DeserializeObject<dynamic>(content);
foreach (var data in prods)
{
var dataGroup = new GroupList
(
data.term_id,
data.name,
data.slug,
data.description,
data.taxonomy
);
Groups.Add(dataGroup);
}
}
The URL I am accessing is actually a page in a website where I call some fucntions to get some data in php and then use json_encode($all); to return json data. When I access the url, I can see all the JSON data.
One example of the data from URL is:
[{"term_id":"64","name":"Argentina","slug":"argentina","term_group":"0","term_taxonomy_id":"64","taxonomy":"product_cat","description":"","parent":"13","count":"20","meta_id":"154","woocommerce_term_id":"64","meta_key":"order","meta_value":"0","cat_ID":"64","category_count":"20","category_description":"","cat_name":"Argentina","category_nicename":"argentina","category_parent":"13"},...]
But the application doesn't recognize the json values when I try to access them such as term_id, name etc. (as seen in code above)
Instead when I run the application I get this error:
Unexpected character encountered while parsing value: <. Path", line 4, position 2
How do I get and use the values from the url in my C# code?

You could use the DynamicJson class to parse the JSON, as far as I know it's the best option.

Your page produces some random text in front of JSON. You can take any HTTP debugger (my favorite is Fiddler, but anything would do) to confirm. Here are first several lines of the response from http://cbbnideas.com/brydens-website/api/ - note that JSON starts at 8th line:
37
<!--All Categories (And Sub Categories)-->
6bd8
[{"term_id":"64","name":"Argentina","slug":"argentina","term_gr...

Related

Parsing & Filtering JSON data from API into C# application

My goal is to retrieve JSON data from "The virus tracker" API and parse it into a label. This is for my IB personal project so I just started learning c#. Fount this old code and tried fixing it, it worked with basic GET API's but it doesn't work with the one I'm using. (English not my main language)
POSTMAN RESPONSE
{
"results": [
{
"total_cases": 5954607,
"total_recovered": 2622507,
"total_unresolved": 2255875,
"total_deaths": 363208,
"total_new_cases_today": 53700,
"total_new_deaths_today": 1659,
"total_active_cases": 45257,
"total_serious_cases": 2698001,
"total_affected_countries": 213,
"source": {
"url": "https://thevirustracker.com/"
}
}
],
"stat": "ok"
}
C# CODE
//Creating Client connection
RestClient restClient = new RestClient("https://thevirustracker.com/free-api?global=stats");
//Creating request to get data from server
RestRequest restRequest = new RestRequest("total_cases", Method.GET);
// Executing request to server and checking server response to the it
IRestResponse restResponse = restClient.Execute(restRequest);
// Extracting output data from received response
string response = restResponse.Content;
// Parsing JSON content into element-node JObject
var jObject = JObject.Parse(restResponse.Content);
//Extracting Node element using Getvalue method
string cases = jObject.GetValue("total_cases").ToString();
label1.Text = (cases);
ERROR
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
My final goal with this code is that label1 says "5954607"
Remember that I'm really new to this so if you can explain the changes you made to the code ill really appreciate it.
You're not using RestRequest correctly or initialized the RestClient wrongly.
If that url you used in the RestClient is the whole url then you don't need a "resource" in the RestRequest.
Due to that mistake you got an HTML response indicated by the error
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
The value of restResponse.Content probably starts with <html and that is not valid JSON.
The Json payload is a bit more complex then you coded for. The results object holds an array with an object that has your stat property.
Putting these fixes together gives you this code.
RestClient restClient = new RestClient("https://thevirustracker.com/free-api?global=stats");
//Creating request to get data from server
RestRequest restRequest = new RestRequest(null, DataFormat.Json);
// Executing request to server and checking server response to the it
IRestResponse restResponse = restClient.Execute(restRequest);
// Extracting output data from received response
string response = restResponse.Content;
// Parsing JSON content into element-node JObject
var jObject = JObject.Parse(restResponse.Content);
//Extracting
// the object has a results property
// that is an array with one item (zero-based)
// on index 0 there is an object
// that has a property total_cases
string cases = (string) jObject["results"][0]["total_cases"];
label1.Text = (cases);

Trouble with json in asp.net mvc

In an MVC application I retrieve a json string from a given server.
Fist of all I retrieve for testing purpose the json with Chrome and I get this
{
ultima_prelucrare: "2013-11-25",
ultima_declaratie: "2013-11-25",
tva_la_incasare: [ ],
tva: null,
telefon: "0745040840",
stare: "INREGISTRAT din data 04 Iulie 2007",
radiata: false,
numar_reg_com: "J40/12836/2007",
meta: {
updated_at: "2016-08-30T19:05:29.922418",
last_changed_at: null
},
judet: "Municipiul București",
impozit_profit: null,
impozit_micro: "2011-01-01",
fax: null,
denumire: "Infosystems4u S.R.L.",
cod_postal: "61954",
cif: "22052442",
adresa: "Aleea Baiut, 9a, Bucuresti",
act_autorizare: null,
accize: null
}
and is OK.
Now back to my app. I already have a model that describe this structure. I have a view for adding a customer in my application with this fields.
In my scenario I want that after providing a value for "cif" field, and then to make a web request against the given server and retrieve the above json .
The json is retrieved but when I try to deserialize with newtonsoft it raise an exception about "[" character. Here I noticed that [ is not enclosed between quote character but is like this how it comes from server.
On very short my code is like (now the code is simply inside the default action in controller, but I can address this later):
//call openapi.ro
string CompanyCUI = "22052442";
// Create a new 'Uri' object with the specified Company ID string.
Uri myUri = new Uri("https://api.openapi.ro/api/companies/"+CompanyCUI+".json");
// Create a new request to the above mentioned URL.
WebRequest myWebRequest = WebRequest.Create(myUri);
//Add the required header to request
myWebRequest.Headers.Add("x-api-key", "8P4RP_kwn71Nt8VG7boFmQb_7NsihyQxT_x7JGcGQkvPdXZH2Q");
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse = myWebRequest.GetResponse();
// Read the response into a stream
var dataStream = myWebResponse.GetResponseStream();
var reader = new StreamReader(dataStream);
var jsonResultString = reader.ReadToEnd();
// Deserialize
var CompanyInfoData = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomerModels>(jsonResultString);
//Feed the model with retrieved data
//...
//Save all
//...
Now supposing that I find what can be wrong with json content, and eventualy how to go further, next step is to pre fill the editbox controls in my form with retrieved values before the user hit the Save button of the form. What bothers me is that I need two buttons inside my form, one for invoking the web request and fill with desired values, and second the save button, and I really don't know how to deal with two buttons inside a single form.
Thank you in advance for any hint
The JSON provided is syntatically valid. When declaring CustomerModels object, make sure that tva_la_incasare attribute is declared as array or list like below:
public List<object> tva_la_incasare { get; set; }

Delete email using mailinator API

I am creating application to access public emails in mailinator. I can view emails but I have difficulties when I am trying to delete them.
https://mailinator.com/apidocs.jsp all examples from documentacion worked except this one.
I have code to POST Http request:
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "msgid", id}
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://api.mailinator.com/api/delete?", content);
var responseString = await response.Content.ReadAsStringAsync();
}
Only error it throws is (405) Method Not Allowed. or Method is not supported by this URL.
So I guess either my url that I'm sending is bad, either my code.
I need some help to figure it out.
According to the API docs you need to pass a valid token with every call. The delete API example looks like this:
curl "https://api.mailinator.com/api/delete?id=1373143878-0-test22&token=..."
The elipsis (...) there needs to be a valid token. So, add the token to your values dictionary.

How to write nested Json web services in c# for windows store app

I'm working on windows store app where i am using a web service which have parameter which are nested like this
userData, #"user_login",
email, #"email",password, #"password",
user_login key contains to key email and password with their value .I Hit the web service in the fiddler and if works i am getting the response the parameter string i used
{
"user_login":{"email" : "mmmmmmmm#fdhfgh.co","password" : "pass1234"}
}
when i am using this parameter string in my code i am getting error of status code 400 bad request due to the parameter string .
here is my code
string content = string.Empty;
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
httpClient.DefaultRequestHeaders.Date = DateTime.Now;
var httpContent = new System.Net.Http.StringContent("{'user_login':[{'email':"mmmmmmmm#fdhfgh.co",'password':'pass1234'}}]", Encoding.UTF8,"application/json");
var httpResponse = await httpClient.PostAsync(" http://localhost/appi/pupil/log_in", httpContent);
content = await httpResponse.Content.ReadAsStringAsync();
help me out with your valuable suggestions.
In your C# code, you're passing in an array (as denoted by the [ ]'s). It doesn't look like your were doing that in Fiddler. It also looks like the [ ]'s aren't formatted properly. I'd try just taking that out.
EDIT:
"{\"user_login\":{\"email\":\"mmmmmmmm#fdhfgh.com\",\"password\":\"pass1234\"}}"
If this is the correct signature, the above JSON would work.
EDIT 2:
var httpResponse = await httpClient.PostAsync(" http://localhost/appi/pupil/log_in", httpContent);
Couldn't help but notice that you had "localhost/appi" instead of "localhost/api". That could possibly be a typo? Along with that leading space.

What is the best way of reading/parsing WEB API 2 IHttpActionResult responses?

I have following web api method:
public IHttpActionResult Get(int id)
{
var person = _personRepository.GetPersonByID(id);
if (person == null)
return NotFound();
return Ok<Person>(person);
}
And following client calling method:
var data = default(IEnumerable<T>);
var response = _client.GetAsync(relativeUri).Result;
response.EnsureSuccessStatusCode(); // Throw on error code.
if (response.IsSuccessStatusCode)
{
//string dataString = response.Content.ReadAsStringAsync().Result;
data = response.Content.ReadAsAsync<IEnumerable<T>>().Result;
}
else
{
//return response status code/reason phrase
}
after ReadAsAsync call is finished, data variable indicates a collection of type T with count matching returned rows but all objects (elements) are having null valued properties or empty.
Actual values are not being populated in properties.
Fiddler shows the JSON string. Even, ReadAsStringAsAsync() method returns JSON string.
Is there a better way to parse JSON into T type using one of ReadAsXXXX() methods?
Thanks,
-Jignesh
I just wanted to update that I have found the root cause of the issue that I was facing.
The code sample that I mentioned is actually the correct way of calling web api methods.
In my case, JSON string was formatted in Camel Casing at server side and at client side, default formtting was used.
this is server side code which was causing the issue:
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
As soon as this was removed, it started working.
Clearly, ReadAsAsync method could not find the matching properties and therefore all values were being dropped.
Thanks,
-Jignesh

Categories