I am trying to display data collected from RestSharp. Just for example i have the following code but don't know how to display the data as it currently is.
private void readJSON()
{
string url = "http://www.jsonurl.com";
var restClient = new RestClient(url);
var request = new RestRequest(Method.GET);
//82.147.22.3
//What we are requesting:value
request.AddParameter("apikey", "xxxxxtheapikeygoesherexxxxx");
restClient.ExecuteAsync<Entry>(request, response =>
{
//What to do with the JSON?
});
}
I know i need to place the JSON between the ExecuteAsync<>() but i want to be able to take the data and for example place it into a listbox. Below is an example of the result given back to me from JSONtoSharp.com. code:
public class Change
{
public string direction { get; set; }
public int amount { get; set; }
public int actual { get; set; }
}
public class itementry
{
public int position { get; set; }
public int prePosition { get; set; }
public int Weeks { get; set; }
public string ar { get; set; }
public string ti { get; set; }
public Change ch { get; set; }
}
public class RootObject
{
public int charDate { get; set; }
public int retrieved { get; set; }
public List<Entry> entries { get; set; }
}
I am sure the answer is simple as glass and I just need help as i am completely lost in this one.. cant find any good documentation to help me out!
Note: This is for C# on Windows Phone 7 using RestSharp and Newtonsoft
restClient.ExecuteAsync<Entry>(request, response =>
{
//Supply your JSON data to a callback
Callback(response.Data);
});
public void Callback(string jsonResponse)
{
var responseList = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
//Assuming you have properly setup binding properties for Listbox, databind listbox here
YourListBox.ItemsSource = responseList.entries;
}
Here JsonConvert is from NewtonSoft package
Related
I'm trying to fetch Symptoms from an API. I can fetch them already and I'm serializing it inside a class succesfully. The result looks like in image that i share at below:
There are just IDs and Names inside them. The second table from API is like that:
So here my Entity Class;
using System.Collections.Generic;
public class SymptomousInBodySublocations
{
public int ID { get; set; }
public string Name { get; set; }
public bool HasRedFlag { get; set; }
public ICollection<BodyLocations> HealthSymptomLocationIDs { get; set; }
public string ProfName { get; set; }
public List<string> Synonyms { get; set; }
}
And my Serialize Method:
public static List<SymptomousInBodySublocations> SymptomsInBodySublocations()
{
var client = new RestClient("https://priaid-symptom-checker-v1.p.rapidapi.com/symptoms/31/man?format=json&language=en-gb");
var request = new RestRequest(Method.GET);
request.AddHeader("x-rapidapi-host", "priaid-symptom-checker-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "<api-key>");
List<SymptomousInBodySublocations> SymptomsInBodySublocationsList = new List<SymptomousInBodySublocations>();
var response = client.Execute<List<SymptomousInBodySublocations>>(request);
foreach(SymptomousInBodySublocations variables in response.Data)
{
SymptomsInBodySublocationsList.Add(variables);
}
return SymptomsInBodySublocationsList;
}
And my BodyLocations Class:
public class BodyLocations
{
public int ID { get; set; }
public string Name { get; set; }
}
In this point when i tried to fetch my data inside my List<BodyLocations>() the response.Data is empty. What should i do?
HealthSymptomLocationIDs isn't an object, looking at the response it is an array of integers.
Changing the field to match the response should populate the field with the integer values from the API
public List<int> HealthSymptomLocationIDs { get; set; }
I am able to handle simple JSON serialization and deserialization but this API response seems little complicated, and I am seeking an advice as to what would be ideal approach to tackle this.
I'm trying to call an API for MVC application.
Goal is to map API data to model.
API endpoint is
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=MyAPIKey
Troubles here are:
JSON data keys have white space in them.
When I tried doing paste special in Visual studio, It gave me a long
list of classes for each date entry separately, because this API
call returns a separate set of information for date.
To solve problem explained in point 1, I used [JsonProperty("1. Information")] in class. And in my code..
public async Task TSI()
{
HttpClient client = new HttpClient();
//Uri uri = new Uri("http://date.jsontest.com/");
Uri uri = new Uri("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
dynamic result = await response.Content.ReadAsAsync<object>();
IEnumerable<dynamic> dObj = JsonConvert.DeserializeObject<dynamic>(result.ToString());
IEnumerable<dynamic> t1 = dObj.FirstOrDefault();
IEnumerable<dynamic> t2 = dObj.LastOrDefault();
dynamic MetaData = t1.FirstOrDefault();
Rootobject ro = new Rootobject();
ro.MetaData = MetaData;
}
PS: I'm relatively new to make API calls and handling them.
I was able to make a call to
date.jsontest.com
and map the API data to model (which I had created using paste special)
//API response
{
"time": "12:53:22 PM",
"milliseconds_since_epoch": 1504875202754,
"date": "09-08-2017"
}
//C# code to map to API data
public class sampleObject
{
public string time { get; set; }
public long milliseconds_since_epoch { get; set; }
public string date { get; set; }
}
My RootObject looks like this:
public class Rootobject
{
[JsonProperty("Meta Data")]
public MetaData MetaData { get; set; }
[JsonProperty("Time Series (1min)")]
public TimeSeries1Min TimeSeries1min { get; set; }
}
public class MetaData
{
[JsonProperty("1. Information")]
public string _1Information { get; set; }
[JsonProperty("2. Symbol")]
public string _2Symbol { get; set; }
[JsonProperty("3. Last Refreshed")]
public string _3LastRefreshed { get; set; }
[JsonProperty("4. Interval")]
public string _4Interval { get; set; }
[JsonProperty("5. Output Size")]
public string _5OutputSize { get; set; }
[JsonProperty("6. Time Zone")]
public string _6TimeZone { get; set; }
}
// I have so many of these sub-classes for dates, which again is an issue
public class TimeSeries1Min
{
public _20170907160000 _20170907160000 { get; set; }
public _20170907155900 _20170907155900 { get; set; }
....
....}
public class _20170907160000
{
public string _1open { get; set; }
public string _2high { get; set; }
public string _3low { get; set; }
public string _4close { get; set; }
public string _5volume { get; set; }
}
public class _20170907155900
{
public string _1open { get; set; }
public string _2high { get; set; }
public string _3low { get; set; }
public string _4close { get; set; }
public string _5volume { get; set; }
}
It is hard to create a model from this json, but you can convert those data to dictionary
var jObj = JObject.Parse(json);
var metadata = jObj["Meta Data"].ToObject<Dictionary<string, string>>();
var timeseries = jObj["Time Series (1min)"].ToObject<Dictionary<string, Dictionary<string, string>>>();
The following code should do what you want
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<Rootobject>(result);
//No idea what you want to do with this line as there is no MetaData property on the root object
obj.MetaData = MetaData;
}
I'm getting json string from webapi like this
{"page":1,"total_results":33,"total_pages":2,"results":
[{"vote_count":8017,"id":603,"video":false,"vote_average":7.9,"title":"The Matrix","popularity":7.82272,"poster_path":"\/lZpWprJqbIFpEV5uoHfoK0KCnTW.jpg","original_language":"en","original_title":"The Matrix","genre_ids":[28,878],"backdrop_path":"\/7u3pxc0K1wx32IleAkLv78MKgrw.jpg","adult":false,"overview":"Set in the 22nd century, The Matrix tells the story of a computer hacker who joins a group of underground insurgents fighting the vast and powerful computers who now rule the earth.","release_date":"1999-03-30"},
{"vote_count":2750,"id":605,"video":false,"vote_average":6.4,"title":"The Matrix Revolutions","popularity":5.073697,"poster_path":"\/sKogjhfs5q3azmpW7DFKKAeLEG8.jpg","original_language":"en","original_title":"The Matrix Revolutions","genre_ids":[12,28,53,878],"backdrop_path":"\/pdVHUsb2eEz9ALNTr6wfRJe5xVa.jpg","adult":false,"overview":"The human city of Zion defends itself against the massive invasion of the machines as Neo fights to end the war at another front while also opposing the rogue Agent Smith.","release_date":"2003-11-05"},
{"vote_count":0,"id":411948,"video":false,"vote_average":0,"title":"Matrix","popularity":1.004394,"poster_path":"\/cseRq8R9RGN66SNUgcD7RJAxBI7.jpg","original_language":"en","original_title":"Matrix","genre_ids":[],"backdrop_path":null,"adult":false,"overview":"John Whitney, Sr. (April 8, 1917 – September 22, 1995) was an American animator, composer and inventor, widely considered to be one of the fathers of computer animation.","release_date":"1971-05-18"}]}
I only want to get title from above string into list.
Here's my code
public List<string> ExtractMoviesList(string movieTitle)
{
using (var client = new HttpClient())
{
// HTTP GET
var response = client.GetAsync(string.Format("{0}{1}", movies_Url, movieTitle)).Result;
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<Movies>>(json.Result);
return result.Select(p=>p.Title).ToList();
}
}
}
There's something wrong with this line of code: var result = JsonConvert.DeserializeObject<List<Movies>>(json.Result); after this line executed the var result is getting just null.
Your problem is that you are trying to deserialize your JSON as a List<T>, but the root object in your JSON is not an array, it's an object. This is easy to see if you format and indent your JSON using, say, https://jsonformatter.curiousconcept.com/:
{
"page":1,
"total_results":33,
"total_pages":2,
"results":[
{
"title":"The Matrix",
// Other fields
},
// Other movies
]
}
The data model to which you are binding your JSON must reflect this outer container object for deserialization to succeed. Luckily http://json2csharp.com/ or Paste JSON as Classes will generate one for you:
public class Movie
{
public string title { get; set; }
public int vote_count { get; set; }
public int id { get; set; }
public bool video { get; set; }
public double vote_average { get; set; }
public double popularity { get; set; }
public string poster_path { get; set; }
public string original_language { get; set; }
public string original_title { get; set; }
public List<object> genre_ids { get; set; }
public string backdrop_path { get; set; }
public bool adult { get; set; }
public string overview { get; set; }
public string release_date { get; set; }
}
public class RootObject
{
public int page { get; set; }
public int total_results { get; set; }
public int total_pages { get; set; }
public List<Movie> results { get; set; }
}
Now you can do:
var result = JsonConvert.DeserializeObject<RootObject>(json.Result);
return result.results.Select(m => m.title).ToList();
Incidentally, if you don't want to create a data model just to extract the titles from this JSON, you can use Json.NET's LINQ to JSON functionality to load and query the JSON directly:
var result = JToken.Parse(json.Result);
return result.SelectTokens("results[*].title").Select(t => (string)t).ToList();
Here I am using SelectTokens() with the JsonPATH wildcard operator [*] to find all entries in the results array.
Working .Net fiddle showing both options.
I have a response from Jira API, require to be deserialized into data model:
com.atlassian.greenhopper.service.sprint.Sprint#40675167[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]
This is actually the information of current sprint for issue.
I need to deserialize it to a model like:
public class Model
{
public string name { get; set; }
...
}
I have already removed all non-required information, like com.atlassian.greenhopper.service.sprint.Sprint#40675167 using Regex pattern \[(.*?)\] so I have brackets and all inside.
Now I stopped completely trying to find the a way to convert this string to a data model.
Found the following thread at the Atlassian Answers page and there appears to be no JSON representation of that inner Object. As shown in the example from that thread:
customfield_10007:[
"com.atlassian.greenhopper.service.sprint.Sprint#a29f07[rapidViewId=<null>,state=CLOSED,name=NORD - Sprint 42,startDate=2013-07-29T06:47:00.000+02:00,endDate=2013-08-11T20:47:00.000+02:00,completeDate=2013-08-14T15:31:33.157+02:00,id=107]",
"com.atlassian.greenhopper.service.sprint.Sprint#769133[rapidViewId=<null>,state=ACTIVE,name=NORD - Sprint 43,startDate=2013-08-14T15:32:47.322+02:00,endDate=2013-08-23T15:32:47.322+02:00,completeDate=<null>,id=117]"
],
The response is indeed a JSON array, but the array itself contains CSV's, so you can make use of the following to parse that:
public class DataObject
{
public string id { get; set; }
public string rapidViewId { get; set; }
public string state { get; set; }
public string name { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string completeDate { get; set; }
public string sequence { get; set; }
}
public class Program
{
private const string sampleStringData =
#"[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]";
static void Main(string[] args)
{
var dataObject = new DataObject();
string[][] splitted;
var sampleWithNoBrackets = sampleStringData.Substring(1,sampleStringData.Length-2);
splitted = sampleWithNoBrackets.Split(',').Select(p => p.Split('=')).ToArray();
dataObject.id = splitted[0][1];
dataObject.rapidViewId = splitted[1][1];
dataObject.state = splitted[2][1];
dataObject.name = splitted[3][1];
dataObject.startDate = splitted[4][1];
dataObject.endDate = splitted[5][1];
dataObject.completeDate = splitted[6][1];
dataObject.sequence = splitted[7][1];
Console.ReadKey();
}
}
Here's the output for the above:
I'm a novice developer for WP. I have some problems with parsing json data. I take it from a website and parse with JSON.Net.
Example of JSON data:
{"openfooty":{"version":"1.0","response":{"status":"ok"},"teams":{"team":[{"id":"660","cdata":"Arsenal"},{"id":"661","cdata":"Chelsea"},{"id":"662","cdata":"Manchester United"},{"id":"663","cdata":"Liverpool"},{"id":"664","cdata":"Newcastle United"},{"id":"665","cdata":"Aston Villa"},{"id":"667","cdata":"Fulham"},{"id":"670","cdata":"Southampton"},{"id":"674","cdata":"Everton"},{"id":"675","cdata":"Tottenham Hotspur"},{"id":"676","cdata":"Manchester City"},{"id":"677","cdata":"Norwich City"},{"id":"678","cdata":"West Bromwich Albion"},{"id":"683","cdata":"Sunderland"},{"id":"684","cdata":"West Ham United"},{"id":"686","cdata":"Wigan Athletic"},{"id":"688","cdata":"Reading"},{"id":"690","cdata":"Stoke City"},{"id":"702","cdata":"Queens Park Rangers"},{"id":"738","cdata":"Swansea City"}]}}}
I need to parse the team names , i.e "arsenal", "chelsea" etc , preferably with their ids and store in a list. The classes i've made (using http://json2csharp.com/#) are :
public class Response
{
public string status { get; set; }
}
public class Team
{
public string id { get; set; }
public string cdata { get; set; }
}
public class Teams
{
public List<Team> team { get; set; }
}
public class Openfooty
{
public string version { get; set; }
public Response response { get; set; }
public Teams teams { get; set; }
}
public class RootObject
{
public Openfooty openfooty { get; set; }
}
I do this in the cs page :
public class Loaddata
{
public Loaddata()
{
if (NetworkInterface.GetIsNetworkAvailable())
{
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://api.openfooty.org/1.0/league.getTeams?api_key=4&league_id=8&format=json"));
}
}
void proxy_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e)
{
if (e.Error != null) return;
{
var o = JObject.Parse(e.Result);
var x= o["openfooty"].First.First["team"];
string name = x.Value<string>();}}
but i dont get the parsed data. help required ! Thanks :)
Why do you go dynamic way like var x= o["openfooty"].First.First["team"]; when you have all the classes declared.
this works
RootObject root = JsonConvert.DeserializeObject<RootObject>(e.Result);
var id = root.openfooty.teams.team[0].id;