Parsing Json in UWP - c#

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);

Related

Invalid Json error during json object convert

I am trying to convert a json response value to c# class value. But when i try to pass into JsonDeserializer that response it throwing error: Invalid Json. Bellow the code example is provided. Also note i am using RestSharp to make that url call. And the example url also provided bellow:
response url: http://api.walmartlabs.com/v1/items?apiKey=3zmwbajjf4ugzqhdtgsf59ac&upc=029986182548
string url = "http://api.walmartlabs.com/v1/items?apiKey=3zmwbajjf4ugzqhdtgsf59ac&upc=029986182548";
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var deserializer = new JsonDeserializer();
var wmr = deserializer.Deserialize<WallMartData>(response);
Model class generated by http://json2csharp.com/
namespace WebApplication2.ViewModels
{
public class Attributes
{
public string color { get; set; }
public string productUrlText { get; set; }
public string uniqueProductId { get; set; }
}
public class GiftOptions
{
}
public class ImageEntity
{
public string thumbnailImage { get; set; }
public string mediumImage { get; set; }
public string largeImage { get; set; }
public string entityType { get; set; }
}
public class WallMartData
{
public int itemId { get; set; }
public int parentItemId { get; set; }
public string name { get; set; }
public double msrp { get; set; }
public double salePrice { get; set; }
public string upc { get; set; }
public string categoryPath { get; set; }
public string shortDescription { get; set; }
public string longDescription { get; set; }
public string brandName { get; set; }
public string thumbnailImage { get; set; }
public string mediumImage { get; set; }
public string largeImage { get; set; }
public string productTrackingUrl { get; set; }
public double standardShipRate { get; set; }
public string color { get; set; }
public bool marketplace { get; set; }
public string modelNumber { get; set; }
public string sellerInfo { get; set; }
public string productUrl { get; set; }
public string customerRating { get; set; }
public int numReviews { get; set; }
public string customerRatingImage { get; set; }
public string categoryNode { get; set; }
public string rhid { get; set; }
public bool bundle { get; set; }
public bool clearance { get; set; }
public bool preOrder { get; set; }
public string stock { get; set; }
public Attributes attributes { get; set; }
public string addToCartUrl { get; set; }
public string affiliateAddToCartUrl { get; set; }
public bool freeShippingOver35Dollars { get; set; }
public GiftOptions giftOptions { get; set; }
public List<ImageEntity> imageEntities { get; set; }
public string offerType { get; set; }
public bool availableOnline { get; set; }
}
}
The response sent is a json array so all you need to do is change the last line to:
var wmr = deserializer.Deserialize<List<WallMartData>>(response);
Basically deserialize into a list of your model.
I've to guess, but the URL sends an array, not a single object of WallMartData.
Try something like this:
List<string> tmp = new List<string>();
using (var sr = new StreamReader("C:\\Temp\\tst.txt")) // tst.txt contains the url-response
{
while(!sr.EndOfStream)
tmp.Add(sr.ReadLine());
}
WallMartData[] x = JsonConvert.DeserializeObject<WallMartData[]>(string.Join("\n", tmp));
In your case it would be:
string url = "http://api.walmartlabs.com/v1/items?apiKey=3zmwbajjf4ugzqhdtgsf59ac&upc=029986182548";
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var deserializer = new JsonDeserializer();
var wmr = deserializer.Deserialize<WallMartData[]>(response); // See the bracer here ;-)
It return a List or Array
Try this
string url = "http://api.walmartlabs.com/v1/items?apiKey=3zmwbajjf4ugzqhdtgsf59ac&upc=029986182548";
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var deserializer = new JsonDeserializer();
var wmr = deserializer.Deserialize<List<WallMartData>>(response);

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);
}
}

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

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);
}
}
}

JSON parsing C# no name variable

I'm trying to deserialize a Json String to a object but I only get 0 and null back.
Here is my code:
string result = "[{\"page\":1,\"pages\":1,\"per_page\":\"50\",\"total\":1},[{\"id\":\"BEL\",\"iso2Code\":\"BE\",\"name\":\"Belgium\",\"region\":{ \"id\":\"ECS\",\"value\":\"Europe & Central Asia(all income levels)\"},\"adminregion\":{ \"id\":\"\",\"value\":\"\"},\"incomeLevel\":{ \"id\":\"OEC\",\"value\":\"High income: OECD\"},\"lendingType\":{ \"id\":\"LNX\",\"value\":\"Not classified\"},\"capitalCity\":\"Brussels\",\"longitude\":\"4.36761\",\"latitude\":\"50.8371\"}]]";
var serializer = new DataContractJsonSerializer(typeof(LandRootObject));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (LandRootObject)serializer.ReadObject(ms);
public class LandRootObject
{
public int page { get; set; }
public int pages { get; set; }
public string per_page { get; set; }
public int total { get; set; }
[DataMember]
public List<Land> land { get; set; }
}
Thanks!
I have tested this method and it's working.
Your entity classes. (I did not code all these classes. They are code generated using paste special.)
public class LandRootObject
{
public int page { get; set; }
public int pages { get; set; }
public string per_page { get; set; }
public int total { get; set; }
}
public class LandBodyObject
{
public string id { get; set; }
public string iso2Code { get; set; }
public string name { get; set; }
public Region region { get; set; }
public Adminregion adminregion { get; set; }
public Incomelevel incomeLevel { get; set; }
public Lendingtype lendingType { get; set; }
public string capitalCity { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
}
public class Region
{
public string id { get; set; }
public string value { get; set; }
}
public class Adminregion
{
public string id { get; set; }
public string value { get; set; }
}
public class Incomelevel
{
public string id { get; set; }
public string value { get; set; }
}
public class Lendingtype
{
public string id { get; set; }
public string value { get; set; }
}
Then the deserialisation method. Your Json has two parts. So I am splitting it in to 2 for deserialisation.
string result = "[{\"page\":1,\"pages\":1,\"per_page\":\"50\",\"total\":1},[{\"id\":\"BEL\",\"iso2Code\":\"BE\",\"name\":\"Belgium\",\"region\":{ \"id\":\"ECS\",\"value\":\"Europe & Central Asia(all income levels)\"},\"adminregion\":{ \"id\":\"\",\"value\":\"\"},\"incomeLevel\":{ \"id\":\"OEC\",\"value\":\"High income: OECD\"},\"lendingType\":{ \"id\":\"LNX\",\"value\":\"Not classified\"},\"capitalCity\":\"Brussels\",\"longitude\":\"4.36761\",\"latitude\":\"50.8371\"}]]";
var parts = result.Split(new[] {",["}, StringSplitOptions.None);
if (parts.Length > 1)
{
var header = parts[0].Replace("[", "");
var jsonHeader = JsonConvert.DeserializeObject<LandRootObject>(header);
var body = "[" + parts[1].Replace("]]","]");
var jsonBody = JsonConvert.DeserializeObject<List<LandBodyObject>>(body);
}
Use List type
var serializer = new DataContractJsonSerializer(typeof(List<LandRootObject>));
// ...
var data = (List<LandRootObject>)serializer.ReadObject(ms);
Edit:
Now I see - your json array consists of 2 different elements. I suppose its [RootObject, Lands]. You better use the Newtonsoft.Json to deserialize the object.
var str = "[{\"page\":1,\"pages\":1,\"per_page\":\"50\",\"total\":1},[{\"id\":\"BEL\",\"iso2Code\":\"BE\",\"name\":\"Belgium\",\"region\":{ \"id\":\"ECS\",\"value\":\"Europe & Central Asia(all income levels)\"},\"adminregion\":{ \"id\":\"\",\"value\":\"\"},\"incomeLevel\":{ \"id\":\"OEC\",\"value\":\"High income: OECD\"},\"lendingType\":{ \"id\":\"LNX\",\"value\":\"Not classified\"},\"capitalCity\":\"Brussels\",\"longitude\":\"4.36761\",\"latitude\":\"50.8371\"}]]";
var arr = JArray.Parse(str);
var rootJson = arr.ElementAt(0).ToString();
var root = JsonConvert.DeserializeObject<LandRootObject>(rootJson);
var landsJson = arr.ElementAt(1).ToString();
root.Lands = JsonConvert.DeserializeObject<List<Land>>(landsJson);
tryto change the above code to following
ms.Position = 0; // change only this line
var data = (LandRootObject)serializer.ReadObject(ms);

Converting Object to JSON string in c#,WP7

I am facing problem when am trying to get a JSON string like
[{Key:{key:value,key:value,key:value,key:value},
key: [{key:value,key:value,key:value,key:value}]
in C#.
my class structure is like this
public class wideeye
{
public listing listing { get; set; }
public listing_images[] listing_images { get; set; }
}
public class listing
{
public string category { get; set; }
public string city { get; set; }
public string country { get; set; }
public string created_at { get; set; }
public string current_publish_date { get; set; }
public string details { get; set; }
public string id { get; set; }
public string industry { get; set; }
public string list_exp_date { get; set; }
public string list_price { get; set; }
public string list_start_date { get; set; }
public string make { get; set; }
public string model { get; set; }
public string open_bid { get; set; }
public string state { get; set; }
public string status { get; set; }
public string title { get; set; }
public string updated_at { get; set; }
public string year { get; set; }
}
public class listing_images
{
public string created_at { get; set; }
public string id { get; set; }
public string listing_id { get; set; }
public string listing_image_content_type { get; set; }
public string listing_image_file_name { get; set; }
public int listing_image_file_size { get; set; }
public string listing_image_updated_at { get; set; }
public string updated_at { get; set; }
}
}
and the code is
listing bid1 =
new listing { category = "electronics", city = "BBSR" };
listing_images bid2 =
new listing_images { created_at = "Instrumentation", id = "10" };
List<listing> obid1 = new List<listing>() { bid1};
List<listing_images> obid2 = new List<listing_images>() { bid2 };
//DataContractJsonSerializer serializer = null;
string sJSON = JsonConvert.SerializeObject(obid1);
string sJSONw = JsonConvert.SerializeObject(obid2);
DataContractJsonSerializer class is very handy.
Add references to System.Runtime.Serialization.dll and System.Servicemodel.Web.dll to your project.
using System.Runtime.Serialization.Json;
...
...
...
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer sr = new DataContractJsonSerializer(obj.GetType());
sr.WriteObject(stream, obj);
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string jsonResult = reader.ReadToEnd();
Of course do proper exceptions handling.
I vote for using JSON.net # http://json.codeplex.com/ Its being adopted by Microsoft and its more efficient that the DataContractJsonSerializer
example of use here : http://james.newtonking.com/projects/json/help/
or if not use the Javascript Serializer
protected static string JsonSerialize(Object obj)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = int.MaxValue };
var json = serializer.Serialize(obj);
return json;
}
Would have left this as a comment but was rather cumbersome:
add a reference to System.Web.MVC to your project and then create the JSON like this:
var jsonOutput = Json(obid1);
This is how I generate JSON in MVC controllers for my AJAX calls. Have not tried it in a Windows mobile app though.
Just a thought.

Categories

Resources