Get all the titles after deserialiaztion json using C# and Json.net - c#

I am using a wikipedia api which contains external links of all places from a wikipedia article. My wikipedia api call is:
https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json
I make c# classes for json object using JsonToCsharp as follows:
public class Geosearch
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public double lat { get; set; }
public double lon { get; set; }
public double dist { get; set; }
public string primary { get; set; }
public string type { get; set; }
public string name { get; set; }
public object dim { get; set; }
public string country { get; set; }
public string region { get; set; }
}
public class Query
{
public List<Geosearch> geosearch { get; set; }
}
public class RootObject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
}
My deserialization code is as follows.With this code I got only one Title. But I want to get all the title from this api. I know I should make a foreach loop, but could not get logic how to implement it.
static void Main(string[] args)
{
WebClient client = new WebClient();
var GeoResponse = client.DownloadString("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json");
RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(GeoResponse);
var firstKey = json.query.geosearch.First().title;
Console.WriteLine(firstKey);
}

This works fine -
var o = new HttpClient();
var res = new StreamReader(o.GetStreamAsync("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json").Result).ReadToEnd() ;
var obj = JsonConvert.DeserializeObject<RootObject>(res).query.geosearch.Select(a => a.title).ToList();
// count == 500
obj.Foreach(a => Console.WriteLine(a));

I just modified my code and It is working perfectly.
var response = client.GetAsync("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<RootObject>(responseString).query.geosearch.Select(a => a.title).ToList();
foreach (var item in obj)
{
Console.WriteLine(item);
}
}
}

Related

How to get values from API?

I apologize for this post because it may seem banal to some people. But I would like to understand the operation of the GET API, unfortunately, somehow I have not found an accessible tutorial. As the best way to learn from examples, could anyone show me how to get the values from the name tag in the easiest way? can be up to textBox.
In xml:
https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=xml
In json:
https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json
Code
public class Result
{
public string id { get; set; }
public string name { get; set; }
public bool hasVariables { get; set; }
public List<string> children { get; set; }
public string levels { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
var json = wc.DownloadString("https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json");
Result result = JsonConvert.DeserializeObject<Result>(json);
richTextBox1.Text = result.name;
}
}
Thank you in advance for your help.
You are missing various classes in order to get your JSON string Deserialized properly. Try like:
public class Results
{
public string id { get; set; }
public string name { get; set; }
public bool hasVariables { get; set; }
public List<string> children { get; set; }
public string levels { get; set; }
}
public class Links
{
public string first { get; set; }
public string self { get; set; }
public string next { get; set; }
public string last { get; set; }
}
public class JsonObject
{
public int totalRecords { get; set; }
public int page { get; set; }
public int pageSize { get; set; }
public Links links { get; set; }
public List<Results> results { get; set; }
}
And then use like:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json");
JsonObject result = JsonConvert.DeserializeObject<JsonObject>(json);
foreach (var res in result.results)
{
MessageBox.Show(res.name);
}
}

Deserialising json C#

I have json as below:
{"data":[{"name":"123","pwd":123},{"name":"456","pwd":456},{"name":"789","pwd":789}],"duration":5309,"query":"myquery","timeout":300}
Using http://json2csharp.com/ I am deserialising it as below:
namespace Test
{
public class Info
{
public string name{ get; set; }
public string pwd{ get; set; }
}
public class Product
{
public Info[] data { get; set; }
public int duration { get; set; }
public string query { get; set; }
public int timeout { get; set; }
}
//code here, function start etc.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new
StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Product myprod = JsonConvert.DeserializeObject<Product>(result);
var results = myprod.data;
}
}
The value of results is {Test.Info[0]} where Test is my namespace name. How do I obtain the actual data?
Your Info class should be
public class Info
{
public string name { get; set; }
public int pwd { get; set; }
}
This should work
var testJson = "{\"data\":[{\"name\":\"123\",\"pwd\":123},{\"name\":\"456\",\"pwd\":456},{\"name\":\"789\",\"pwd\":789}],\"duration\":5309,\"query\":\"myquery\",\"timeout\":300}";
var product = JsonConvert.DeserializeObject<Product>(testJson);

Parsing Json in UWP

I’m working on UWP and I’m trying to parse this Json but can't understand why this code can't work please anyone can check it with me need help. Thank you. And there is a problem in getting the list variable (List).
Any help is appreciated.
namespace testapi2
{
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
jsonCall();
}
public async void jsonCall()
{
List<Result> listResult = new List<Result>();
var client = new HttpClient();
HttpResponseMessage response =
await client.GetAsync(new Uri("http://api-public.guidebox.com/v1.43/Tunisia/rKgEWJbFg0kgEHrcGXPKhPDo0XtTafyC/movies/all/250/250"));
client.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
var array = await response.Content.ReadAsStringAsync();
JsonArray ja = JsonValue.Parse(array).GetArray();
for (uint i = 0; i < ja.Count; i++)
{
//Debug.WriteLine(i);
Result result = new Result();
int id = Convert.ToInt32(ja.GetObjectAt(i).GetNamedValue("id"));
string title = ja.GetObjectAt(i).GetNamedString("title");
int release_year = Convert.ToInt32(ja.GetObjectAt(i).GetNamedNumber("release_year"));
int themoviedb = Convert.ToInt32(ja.GetObjectAt(i).GetNamedString("themoviedb"));
string original_title = ja.GetObjectAt(i).GetNamedString("original_title");
// List<object> alternate_titles = ja.GetObjectAt(i).GetNamedArray("alternate_titles");
string imdb = ja.GetObjectAt(i).GetNamedString("imdb");
bool pre_order = ja.GetObjectAt(i).GetNamedBoolean("pre_order");
bool in_theaters = ja.GetObjectAt(i).GetNamedBoolean("in_theaters");
string release_date = ja.GetObjectAt(i).GetNamedString("release_date");
string rating = ja.GetObjectAt(i).GetNamedString("rating");
int rottentomatoes = Convert.ToInt32(ja.GetObjectAt(i).GetNamedString("rottentomatoes"));
string freebase = ja.GetObjectAt(i).GetNamedString("freebase");
int wikipedia_id = Convert.ToInt32(ja.GetObjectAt(i).GetNamedString("wikipedia_id"));
string metacritic = ja.GetObjectAt(i).GetNamedString("metacritic");
string common_sense_media = ja.GetObjectAt(i).GetNamedString("common_sense_media");
string poster_120x171 = ja.GetObjectAt(i).GetNamedString("poster_120x171");
string poster_240x342 = ja.GetObjectAt(i).GetNamedString("poster_240x342");
string poster_400x570 = ja.GetObjectAt(i).GetNamedString("poster_400x570");
listResult.Add(result);
}
// Debug.WriteLine("hello", listResult);
list.ItemsSource = listResult;
}
}
}
Your api return a value of jsonObject type and you try to convert that to an array.
you can try this.
At first add Newtonsoft.Json from manage nuget package of add reference.
Now paste your json response to this site jsonToC# and add generated to classes to your project. For your reference api you will get 2 class like this.
public class Result
{
public int id { get; set; }
public string title { get; set; }
public int release_year { get; set; }
public int themoviedb { get; set; }
public string original_title { get; set; }
public List<object> alternate_titles { get; set; }
public string imdb { get; set; }
public bool pre_order { get; set; }
public bool in_theaters { get; set; }
public string release_date { get; set; }
public string rating { get; set; }
public int rottentomatoes { get; set; }
public string freebase { get; set; }
public int wikipedia_id { get; set; }
public string metacritic { get; set; }
public string common_sense_media { get; set; }
public string poster_120x171 { get; set; }
public string poster_240x342 { get; set; }
public string poster_400x570 { get; set; }
}
public class RootObject
{
public int total_results { get; set; }
public int total_returned { get; set; }
public List<Result> results { get; set; }
}
then add following code & will get all data at result.
var json = await response.Content.ReadAsStringAsync();
var result= JsonConvert.DeserializeObject<RootObject>(json);

Json deserialize from wikipedia api with c#

I have a wikipedia api with json format. Now I want to get the extract information from this api. I want to make it dynamic for any wikipedia api. [My wikipedia api][1]. I got following information from jsontoCsharp
namespace Json_deserialize
{
public class pageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
}
public class Query
{
public Dictionary<string, pageval> pages { get; set; }
}
public class Limits
{
public int extracts { get; set; }
}
public class RootObject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
public Limits limits { get; set; }
}
class Short_text
{
public static RichTextBox txt1 = new RichTextBox();
public static void shortText()
{
using (WebClient wc = new WebClient())
{
var client = new WebClient();
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Neuschwanstein%20Castle&redirects="); ;
pageval m = JsonConvert.DeserializeObject<pageval>(response);
string result = m.extract;
txt1.Text = result;
}
}
}
}
I want to make such a coding which should be dynamic. That means the id 240912 should be varied in time. I tried a lot. but cannot get a satisfied result.
All JSON objects are essentially dictionaries. However, it usually makes sense to represent them as classes in C#, assuming the schema is constant. For cases where property names are not always the same, it's impossible to write a class to represent the object; so you much use dynamic or a dictionary
public class pageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
}
public class Query
{
public Dictionary<string, pageval> pages { get; set; }
}
public class Limits
{
public int extracts { get; set; }
}
public class RootObject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
public Limits limits { get; set; }
}
To get the extract:
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Neuschwanstein%20Castle&redirects="); ;
var responseJson = JsonConvert.DeserializeObject<RootObject>(response);
var firstKey = responseJson.query.pages.First().Key;
var extract = responseJson.query.pages[firstKey].extract;

parsing json response is null

I have a problem with parsing json.
The json data is here: http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e.
I created some classes with json2csharp, but search is null:
var url = "http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e";
WebClient client = new WebClient();
var json = client.DownloadString(url);
var search = JsonConvert.DeserializeObject<ServiceResponse>(json);
public class Engine
{
public int FMEBuildNumber { get; set; }
public string FMEHostName { get; set; }
public string FMEInstanceName { get; set; }
public int currentJobID { get; set; }
public int maxTransactionResultFailure { get; set; }
public int maxTransactionResultSuccess { get; set; }
public int resultFailureCount { get; set; }
public int resultSuccessCount { get; set; }
public int transactionPort { get; set; }
}
public class Engines
{
public List<Engine> engine { get; set; }
}
public class ServiceResponse
{
public string requestURI { get; set; }
public string token { get; set; }
public Engines engines { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class RootObject
{
[JsonProperty("serviceResponse")]
public ServiceResponse ServiceResponse { get; set; }
}
How about going dynamic way using Json.Net? (without using any class generated by http://json2csharp.com/)
var url = "http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e";
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString(url);
dynamic dynobj = JsonConvert.DeserializeObject(json);
foreach (var engine in dynobj.serviceResponse.engines.engine)
{
Console.WriteLine("{0} {1}", engine.FMEInstanceName, engine.transactionPort);
}
}

Categories

Resources