How to parse the Json data in windows phone 8 - c#

I am new to windows phone 8 development. I am working on application in which I need parse the Json. so I am not able to get the following data in windows phone 8.
{
"response":{
"errorFlag":0,
"Score Detail":{
"39":[
{
"test_date":"2013-06-28",
"total_marks":"50",
"score":"14"
},
{
"test_date":"2013-08-08",
"total_marks":"20",
"score":"20"
}
],
"40":[
{
"test_date":"2013-08-08",
"total_marks":"20",
"score":"20"
},
{
"test_date":"2013-08-08",
"total_marks":"30",
"score":"20"
},
{
"test_date":"2013-08-08",
"total_marks":"30",
"score":"20"
}
],
"50":[
{
"test_date":"2013-08-08",
"total_marks":"30",
"score":"20"
}
]
}
}
}
I am trying to parse the data in the following way
namespace testscore
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Mainpage_Loaded);
}
void Mainpage_Loaded(object sender, RoutedEventArgs e)
{
WebClient webClient1 = new WebClient();
webClient1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient1_DownloadStringCompleted);
webClient1.DownloadStringAsync(new Uri("some link"));
}
public void webClient1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);
MessageBox.Show(e.Result.ToString());
foreach (var res in rootObject.response.ScoreDetail)
{
string rs = res.Key;
MessageBox.Show(rs.ToString());
......
}
}
public class RootObject
{
public Response response { get; set; }
}
public class Response
{
public int errorFlag { get; set; }
[JsonProperty("Score Detail")]
public JObject ScoreDetail { get; set; }
}
Here I am to getting key value (here it is 39) but I am not able to get the values of the score, testdate and marks. please help me in parsing these details.
Thanks in advance.

I propose you to build classes of your json :
public class RootObject
{
public Response response { get; set; }
}
public class Response
{
public int errorFlag { get; set; }
[JsonProperty("Score Detail")]
public JObject ScoreDetail { get; set; }
}
You can use them on the DownloadStringCompleted event :
public void webClient1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
RootObject root = JsonConvert.DeserializeObject<RootObject>(e.Result);
JObject obj = root.response.ScoreDetail;
foreach (KeyValuePair<string, JToken> pair in obj)
{
string key = pair.Key; // here you got 39.
foreach (JObject detail in pair.Value as JArray)
{
string date = detail["test_date"].ToString();
string score = detail["score"].ToString();
string total_marks = detail["total_marks"].ToString();
}
}
}
Hope it helps !

var result= JObject.Parse(response)["response"]["ScoreDetail"];
foreach (var item in result)
{
// Code to store the result
}

Related

Merging C# code in Xamarin Android

I got the code of detecting poor grammar from here - Detecting Poor grammar
I am new to C# and Xamarin. I want to merge this code into my speech to text conversion app.
I tried to do it, but I am not getting the desired results.
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.OS;
using Android.Speech;
using Android.Util;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
namespace SpeechToText
{
[Activity(Label = "SpeechToText", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, IRecognitionListener
{
public const string Tag = "VoiceRec";
SpeechRecognizer Recognizer { get; set; }
Intent SpeechIntent { get; set; }
TextView Label { get; set; }
TextView Label1 { get; set; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Recognizer = SpeechRecognizer.CreateSpeechRecognizer(this);
Recognizer.SetRecognitionListener(this);
SpeechIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
SpeechIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
SpeechIntent.PutExtra(RecognizerIntent.ExtraCallingPackage, PackageName);
var button = FindViewById<Button>(Resource.Id.btn);
button.Click += ButtonClick;
var Grammarbutton = FindViewById<Button>(Resource.Id.btn1);
Grammarbutton.Click += new EventHandler(ButtonClick2);
Label = FindViewById<TextView>(Resource.Id.tv);
Label1 = FindViewById<TextView>(Resource.Id.tv1);
}
private void ButtonClick(object sender, EventArgs e)
{
Recognizer.StartListening(SpeechIntent);
}
public void OnResults(Bundle results)
{
var matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
if (matches != null && matches.Count > 0)
{
Label.Text = matches[0];
}
}
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
for (; ; )
{
Console.Write("Text to check: ");
var text = Label.Text;
if (string.IsNullOrEmpty(text)) break;
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
public void OnReadyForSpeech(Bundle #params)
{
Log.Debug(Tag, "OnReadyForSpeech");
}
public void OnBeginningOfSpeech()
{
Log.Debug(Tag, "OnBeginningOfSpeech");
}
public void OnEndOfSpeech()
{
Log.Debug(Tag, "OnEndOfSpeech");
}
public void OnError([GeneratedEnum] SpeechRecognizerError error)
{
Log.Debug("OnError", error.ToString());
}
public void OnBufferReceived(byte[] buffer) { }
public void OnEvent(int eventType, Bundle #params) { }
public void OnPartialResults(Bundle partialResults) { }
public void OnRmsChanged(float rmsdB) { }
}
}
class GingerItApi
{
public CheckResult Check(string text)
{
var request = WebRequest.Create($"https://services.gingersoftware.com/Ginger/correct/jsonSecured/GingerTheTextFull?callback=jQuery172015406464511272344_1490987331365&apiKey=GingerWebSite&lang=US&clientVersion=2.0&text={text}&_=1490987518060") as HttpWebRequest;
WebResponse response = null;
try
{
response = request.GetResponse();
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string data = reader.ReadToEnd();
var first = data.IndexOf('{');
var last = data.LastIndexOf('}');
var json = data.Substring(first, last - first + 1);
return JsonConvert.DeserializeObject<CheckResult>(json);
}
}
}
catch (Exception)
{
throw;
}
return null;
}
}
public class LrnFrgOrigIndx
{
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Mistake
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("CanAddToDict")]
public bool CanAddToDict { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Suggestion
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("LrnCatId")]
public int LrnCatId { get; set; }
[JsonProperty("Text")]
public string Text { get; set; }
}
public class Correction
{
[JsonProperty("Confidence")]
public int Confidence { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("LrnFrg")]
public string LrnFrg { get; set; }
[JsonProperty("LrnFrgOrigIndxs")]
public IList<LrnFrgOrigIndx> LrnFrgOrigIndxs { get; set; }
[JsonProperty("Mistakes")]
public IList<Mistake> Mistakes { get; set; }
[JsonProperty("ShouldReplace")]
public bool ShouldReplace { get; set; }
[JsonProperty("Suggestions")]
public IList<Suggestion> Suggestions { get; set; }
[JsonProperty("To")]
public int To { get; set; }
[JsonProperty("TopLrnCatId")]
public int TopLrnCatId { get; set; }
[JsonProperty("Type")]
public int Type { get; set; }
[JsonProperty("UXFrgFrom")]
public int UXFrgFrom { get; set; }
[JsonProperty("UXFrgTo")]
public int UXFrgTo { get; set; }
}
public class Sentence
{
[JsonProperty("FromIndex")]
public int FromIndex { get; set; }
[JsonProperty("IsEnglish")]
public bool IsEnglish { get; set; }
[JsonProperty("ToIndex")]
public int ToIndex { get; set; }
}
public class CheckResult
{
[JsonProperty("Corrections")]
public IList<Correction> Corrections { get; set; }
[JsonProperty("Sentences")]
public IList<Sentence> Sentences { get; set; }
}
I want to get the recognized speech, send it to grammar corrector, and display the output.
Please help me to solve this, or at least help me to further research the problem.
Thank you.
You have put an infinite loop in your code. Please remove it.
For example:
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
Console.Write("Text to check: ");
var text = Label.Text;
if (!string.IsNullOrEmpty(text))
{
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Label1.Text = "Looks okay.\n";
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
And the result is:

JSON value is sometimes a string and sometimes an object

I have some JSON that can come in two different formats. Sometimes the location value is a string, and sometimes it is an object. This is a sample of the first format:
{
"result": [
{
"upon_approval": "Proceed to Next Task",
"location": "",
"expected_start": ""
}
]
}
Class definitions for this:
public class Result
{
public string upon_approval { get; set; }
public string location { get; set; }
public string expected_start { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
}
Here is the JSON in the second format:
{
"result": [
{
"upon_approval": "Proceed to Next Task",
"location": {
"display_value": "Corp-HQR",
"link": "https://satellite.service-now.com/api/now/table/cmn_location/4a2cf91b13f2de00322dd4a76144b090"
},
"expected_start": ""
}
]
}
Class definitions for this:
public class Location
{
public string display_value { get; set; }
public string link { get; set; }
}
public class Result
{
public string upon_approval { get; set; }
public Location location { get; set; }
public string expected_start { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
}
When deserializing, I get errors when the JSON format does not match my classes, but I don't know ahead of time which classes to use because the JSON format changes. So how can I dynamically get these two JSON formats to deserialize into one set of classes?
This is how I am deserializing now:
JavaScriptSerializer ser = new JavaScriptSerializer();
ser.MaxJsonLength = 2147483647;
RootObject ro = ser.Deserialize<RootObject>(responseValue);
To solve this problem you'll need to make a custom JavaScriptConverter class and register it with the serializer. The serializer will load the result data into a Dictionary<string, object>, then hand off to the converter, where you can inspect the contents and convert it into a usable object. In short, this will allow you to use your second set of classes for both JSON formats.
Here is the code for the converter:
class ResultConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new List<Type> { typeof(Result) }; }
}
public override object Deserialize(IDictionary<string, object> dict, Type type, JavaScriptSerializer serializer)
{
Result result = new Result();
result.upon_approval = GetValue<string>(dict, "upon_approval");
var locDict = GetValue<IDictionary<string, object>>(dict, "location");
if (locDict != null)
{
Location loc = new Location();
loc.display_value = GetValue<string>(locDict, "display_value");
loc.link = GetValue<string>(locDict, "link");
result.location = loc;
}
result.expected_start = GetValue<string>(dict, "expected_start");
return result;
}
private T GetValue<T>(IDictionary<string, object> dict, string key)
{
object value = null;
dict.TryGetValue(key, out value);
return value != null && typeof(T).IsAssignableFrom(value.GetType()) ? (T)value : default(T);
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
}
Then use it like this:
var ser = new JavaScriptSerializer();
ser.MaxJsonLength = 2147483647;
ser.RegisterConverters(new List<JavaScriptConverter> { new ResultConverter() });
RootObject ro = serializer.Deserialize<RootObject>(responseValue);
Here is a short demo:
class Program
{
static void Main(string[] args)
{
string json = #"
{
""result"": [
{
""upon_approval"": ""Proceed to Next Task"",
""location"": {
""display_value"": ""Corp-HQR"",
""link"": ""https://satellite.service-now.com/api/now/table/cmn_location/4a2cf91b13f2de00322dd4a76144b090""
},
""expected_start"": """"
}
]
}";
DeserializeAndDump(json);
Console.WriteLine(new string('-', 40));
json = #"
{
""result"": [
{
""upon_approval"": ""Proceed to Next Task"",
""location"": """",
""expected_start"": """"
}
]
}";
DeserializeAndDump(json);
}
private static void DeserializeAndDump(string json)
{
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new List<JavaScriptConverter> { new ResultConverter() });
RootObject obj = serializer.Deserialize<RootObject>(json);
foreach (var result in obj.result)
{
Console.WriteLine("upon_approval: " + result.upon_approval);
if (result.location != null)
{
Console.WriteLine("location display_value: " + result.location.display_value);
Console.WriteLine("location link: " + result.location.link);
}
else
Console.WriteLine("(no location)");
}
}
}
public class RootObject
{
public List<Result> result { get; set; }
}
public class Result
{
public string upon_approval { get; set; }
public Location location { get; set; }
public string expected_start { get; set; }
}
public class Location
{
public string display_value { get; set; }
public string link { get; set; }
}
Output:
upon_approval: Proceed to Next Task
location display_value: Corp-HQR
location link: https://satellite.service-now.com/api/now/table/cmn_location/4a2cf91b13f2de00322dd4a76144b090
----------------------------------------
upon_approval: Proceed to Next Task
(no location)

How do I get the top 5 albums of an artist from the Spotify Web API?

I am trying to build a site using ASP.NET MVC 4 and C# to search for the top 5 albums of a musical artist using the Spotify web api.
Here is my code so far:
public ActionResult Result(string Artist)
{
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://api.spotify.com/");
// what goes here to authenticate and get the info?
return View();
}
I can not find information that tells me how to authenticate and then retrieve the information using C#.
Edit: I should mention that I am an absolute beginner with this stuff and while I did read the spotify api reference, it did not help me because it does not explain enough detail.
For example the web api user guide talks about GET, POST, etc but does not give any code to help explain how to use it. The only code on there is:
$ curl -H "Authorization: Basic Yjc...cK" -d grant_type=refresh_token -d refresh_token=AQD...f0 "https://accounts.spotify.com/api/token"
{
"error": "invalid_client",
"error_description": "Invalid client secret"
}
Which is confusing to me because I don't know where to put it, I don't know what language the code is, etc.
There are no C# examples that I can find. Even the code examples are all javascript which does not help me.
You should see this maybe help to you
TagSearch
using System;
using System.Net;
using System.Text;
using System.Linq;
using System.Collections.Generic;
namespace TagSearch.Plugins
{
public class Spotify : IClass
{
#region JsonParseData
public class Rootobject
{
public Tracks tracks { get; set; }
}
public class Tracks
{
public List<Item> items { get; set; }
}
public class Item
{
public Album album { get; set; }
public List<Artist> artists { get; set; }
public int disc_number { get; set; }
public string name { get; set; }
public int track_number { get; set; }
}
public class Album
{
public string href { get; set; }
public string release_date { get; set; }
public string release_date_precision { get; set; }
public List<Image> images { get; set; }
public string name { get; set; }
}
public class Image
{
public int height { get; set; }
public string url { get; set; }
public int width { get; set; }
}
public class Artist
{
public string name { get; set; }
}
#endregion
protected Dictionary<String, int> _TempTotal;
protected Dictionary<String, List<ITag>> _TempTag;
private object _Lock = new object();
public Spotify()
{
JParse = new System.Text.Json.JsonParser();
_TempTotal = new Dictionary<string, int>();
_TempTag = new Dictionary<String, List<ITag>>();
}
public override void Search(string Name)
{
GetInfo(Name);
}
protected override void GetInfo(string Name)
{
lock (_Lock)
{
_TempTotal.Add(Name, -1);
_TempTag.Add(Name, new List<ITag>());
}
var web = new IWebClient();
web.DownloadDataCompleted += DownloadDataCompleted;
web.DownloadDataAsync(new Uri("https://api.spotify.com/v1/search?&type=track&limit=50&q=" + Uri.EscapeDataString(Name.ToLower())), new IWebClient.WebClientState(Name, 1, null));
while (_TempTotal[Name] != _TempTag[Name].Count) { System.Threading.Thread.Sleep(1000); }
OnEvent(Name,_TempTag[Name]);
_TempTotal.Remove(Name);
_TempTag.Remove(Name);
base.GetInfo(Name);
}
protected void DownloadDataCompleted(dynamic sender, dynamic e)
{
if (e.Result != null)
{
string Name = e.UserState.Name;
switch ((int)e.UserState.State)
{
case 1:
var _RootObject = JParse.Parse<Rootobject>(Encoding.UTF8.GetString(e.Result));
_TempTotal[Name] = _RootObject.tracks.items.Count;
foreach (var Json in _RootObject.tracks.items)
{
var web = new IWebClient();
web.DownloadDataCompleted += DownloadDataCompleted;
web.DownloadDataAsync(new Uri(Json.album.href), new IWebClient.WebClientState(Name, 2, new ITag(this.GetType(), Json.name, Json.album.name, Json.artists[0].name, null, DateTime.MinValue, Json.disc_number, Json.track_number)));
System.Threading.Thread.Sleep(250);
}
sender.Dispose();
break;
case 2:
var Json2 = JParse.Parse<Album>(System.Text.Encoding.UTF8.GetString(e.Result));
e.UserState.State = 3;
switch ((string)Json2.release_date_precision)
{
case "year": e.UserState.Tag.RelaseDate = DateTime.Parse(Json2.release_date + "-01-01"); break;
case "month": e.UserState.Tag.RelaseDate = DateTime.Parse(Json2.release_date + "-01"); break;
case "day": e.UserState.Tag.RelaseDate = DateTime.Parse(Json2.release_date); break;
}
sender.DownloadDataAsync(new Uri(Json2.images[0].url), e.UserState);
break;
case 3:
e.UserState.Tag.Cover = e.Result;
_TempTag[Name].Add(e.UserState.Tag);
sender.Dispose();
break;
}
}
}
}
}

Parsing Multiple Json Rows in windows phone

My json response which i am generating from php :
{"name":"abhi","age":"20","id":"1"}
{"name":"abhi","age":"21","id":"4"}
And the c# code is:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Load(textBox1.Text);
}
public void Load(string keyword)
{
var client = new RestClient("http://localhost/query.php?name="+keyword);
var request = new RestRequest(Method.GET);
//request.AddParameter("name", keyword);
/*request.AddParameter("v", "1.0");
request.AddParameter("q", keyword);
request.AddParameter("hl", "id");
request.AddParameter("rsz", 5);*/
client.ExecuteAsync<RootObject>(request, (response) =>
{
// var resp = response.Data.ToString();
// var respLines = resp.Split('\n');
RootObject rootObject=response.Data;
listBox1.Items.Clear();
if (rootObject == null)
MessageBox.Show("null");
else
{
listBox1.Items.Add(rootObject.age+" " + rootObject.name);
}
});
}
}
}
public class RootObject
{
public string name { get; set; }
public string age { get; set; }
public string id { get; set; }
}
i am able to fetch the first row but not for multiple rows. Anyone has any idea how to fetch multiple rows in json format. How to create multiple objects of json and populate them?
That does not look like valid JSON, try returning a JSON array from PHP:
{
"rows": [
{"name":"abhi","age":"20","id":"1"},
{"name":"abhi","age":"21","id":"4"}
]
}
These would be the corresponding C# classes for deserialization:
public class Row
{
public string name { get; set; }
public string age { get; set; }
public string id { get; set; }
}
public class RootObject
{
public List<Row> rows { get; set; }
}
And you can add your rows with:
foreach (var row in rootOject.rows)
{
listBox1.Items.Add(row.age+" " + row.name);
}

How to read this JSON on Windows Phone?

I have to read this JSON :
[
{"id":"2","code":"jne","name":"JNE"},
{"id":"5","code":"pcp","name":"PCP"},
{"id":"1","code":"pos","name":"Pos Indonesia"},
{"id":"6","code":"wahana","name":"Wahana"}
]
I have tried this :
[DataContract]
public class Ekspedisi
{
[DataMember]
public int id { get; set; }
[DataMember]
public String code { get; set; }
[DataMember]
public String name { get; set; }
}
and this:
public static Ekspedisi[] res;
string link5 = "http://www.ongkoskirim.com/api/0.2/?id=OAL66afd139a386fee6dc5a5597abd7daba&q=expedition"
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(link5), UriKind.Absolute);
and this :
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
var ser = new DataContractJsonSerializer(typeof(Ekspedisi));
res = (Ekspedisi[])ser.ReadObject(e.Result);
for (int i = 0; i < length; i++)
{
Debug.WriteLine(res[i].id+","+res[i].name);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
}
}
But it always showing invalidCastException. Can anyone help me?
When you are deserialising the JSON, you are using the type of Ekspedisi even though you are returning a collection. If you change this line of code:
var ser = new DataContractJsonSerializer(typeof(Ekspedisi));
to
var ser = new DataContractJsonSerializer(typeof(IEnumerable<Ekspedisi>));
which is a collection of your type; you will find you no longer receive the exception.

Categories

Resources