JavaScriptSerializer.Deserialize() into a dictionary - c#

I am trying to parse Open Exchange Rates JSON in Json, and I'm using this approach:
HttpWebRequest webRequest = GetWebRequest("http://openexchangerates.org/latest.json");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
}
var serializer = new JavaScriptSerializer();
CurrencyRateResponse rateResponse = serializer.Deserialize<CurrencyRateResponse>(jsonResponse);
If I understand the JavaScriptSerializer.Deserialize properly I need to define and object to turn the Json into.
I can successfully serialize it using datatypes like this:
public class CurrencyRateResponse
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string basePrice { get; set; }
public CurrencyRates rates { get; set; }
}
public class CurrencyRates
{
public string AED { get; set; }
public string AFN { get; set; }
public string ALL { get; set; }
public string AMD { get; set; }
}
I would like to be able to replay "CurrencyRates rates" with something like:
public Dictionary<string, decimal> rateDictionary { get; set; }
but the parser always returns the rateDictionary as null. Any idea if this is possible, or do you have a better solution?
Edit:
Json looks like this:
{
"disclaimer": "this is the disclaimer",
"license": "Data collected from various providers with public-facing APIs",
"timestamp": 1328880864,
"base": "USD",
"rates": {
"AED": 3.6731,
"AFN": 49.200001,
"ALL": 105.589996,
"AMD": 388.690002,
"ANG": 1.79
}
}

If your json is like:
{"key":1,"key2":2,...}
then you should be able to do:
Dictionary<string, string> rateDict = serializer.Deserialize<Dictionary<string, string>>(json);
This compiles:
string json = "{\"key\":1,\"key2\":2}";
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = ser.Deserialize<Dictionary<string, int>>(json);
You should be able to figure it out yourself from here.

This code works with your sample data
public class CurrencyRateResponse
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string #base { get; set; }
public Dictionary<string,decimal> rates { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var obj = ser.Deserialize<CurrencyRateResponse>(json);
var rate = obj.rates["AMD"];

Below code will work fine, CurrencyRates is collection so that by using List we can take all reates.
This should work!!
public class CurrencyRateResponse
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string basePrice { get; set; }
public List<CurrencyRates> rates { get; set; }
}
public class CurrencyRates
{
public string AED { get; set; }
public string AFN { get; set; }
public string ALL { get; set; }
public string AMD { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var obj = ser.Deserialize<CurrencyRateResponse>(json);
var rate = obj.rates["AMD"];

Related

Null when trying to load a JSON from Root PCL Xamarin

Hi when trying to load a JSON file from the root of my PCL it breaks on this line Using (var reader = new StreamReader(stream)) and says its null.
here is the full method for loadJson()
public void LoadJson()
{
//Loads the JSON File in the Solution and Finds Correct ID of Accordion Hopefully!!
var assembly = typeof(App).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("MCETimeTest.TimeSheet.json");
string jsonString = "";
using (var reader = new StreamReader(stream))
{
jsonString = reader.ReadToEnd();
};
uoObj = JsonConvert.DeserializeObject<RootObject>(jsonString);
}
Edit: when stepping through the code stream is always null
and my classes for my json are:
//JSON Classes
public class RootObject
{
public List<LineItem> LineItems { get; set; }
}
public class Checks
{
public DateTime TheDate { get; set; }
public string JobNumber { get; set; }
public string CustomerName { get; set; }
public TimeSpan On1 { get; set; }
public TimeSpan Off1 { get; set; }
public TimeSpan On2 { get; set; }
public TimeSpan Off2 { get; set; }
public string Description { get; set; }
public string SingleHours { get; set; }
public string TimeHalfHours { get; set; }
public string DoubleHours { get; set; }
}
public class LineItem
{
public string Id { get; set; }
public string Customer { get; set; }
public List<Checks> Checks { get; set; }
}
Also looking over the solution it turns out that the JSON File in the root was not an Embedded Resource. After changing it, it works! sorry for the hassle!

UWP Get array from json Url

I'm using a class to get data from json to my main page and in my json i have an array i want to get them to my Main Page Here's my class code
class WeatherDays
{
public async static Task<day> GetWeather(double lat, double lon)
{
var http = new HttpClient();
var responce = await http.GetAsync("http://a3ane.com/omarNasar/d.php");
var result = await responce.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(day));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (day)serializer.ReadObject(ms);
return data;
}
}
[DataContract]
public class Omarnasar
{
[DataMember]
public string w_id { get; set; }
[DataMember]
public string w_note_tody { get; set; }
[DataMember]
public string w_date { get; set; }
[DataMember]
public string w_time { get; set; }
[DataMember]
public string w_tody_one { get; set; }
[DataMember]
public string w_temperature_one { get; set; }
[DataMember]
public string w_humidity_one { get; set; }
[DataMember]
public string w_note_one { get; set; }
[DataMember]
public string w_tody_two { get; set; }
[DataMember]
public string w_temperature_two { get; set; }
[DataMember]
public string w_humidity_two { get; set; }
[DataMember]
public string w_note_two { get; set; }
[DataMember]
}
[DataContract]
public class day
{
[DataMember]
public List<Omarnasar> omarnasar { get; set; }
}
}
and my problem is i don't know how to get then to my main page using the task here's my try on MainPage
day week = await WeatherDays.GetWeather(20.0, 30.0);
temp1.Text = week.omarnasr.
I don't know how to use them can anyone help my !!!
I think this is what you want
StringBuilder sb = new StringBuilder();
foreach(var obj in week.omarnasr)
{
sb.Append(obj.w_temperature_one + " ");
}
temp1.Text = sb.ToString();

JSON Deserialization to get some particular objects and Serialize with new Json format using C#

For my project I need to Deserialize a long JSON data from Wikipedia. Then I need to get some particular information like Title, Extract, Thumbnail Source, Co-ordinates from that JSON. After getting all these data I need to serialize it again in a new formatted JSON.Hence I wrote a code for this.But having lot of problem with this code. I gave a description of every error beside my coding.
I am using this api from wikipedia
https://en.wikipedia.org/w/api.php?format=json&action=query&redirects=1&generator=geosearch&prop=extracts|coordinates|pageimages&ggslimit=20&ggsradius=1000&ggscoord=52.5243700|13.4105300&&formatversion=2&exintro=1&explaintext=1&exlimit=20&coprop=type|dim|globe&colimit=20&piprop=thumbnail&pithumbsize=400&pilimit=20
My C# object for this json is as below-
public class Coordinate
{
public double lat { get; set; }
public double lon { get; set; }
public string primary { get; set; }
public string type { get; set; }
public string dim { get; set; }
public string globe { get; set; }
}
public class Thumbnail
{
public string source { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Page
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
public List<Coordinate> coordinates { get; set; }
public Thumbnail thumbnail { get; set; }
}
public class Query
{
public List<Page> pages { get; set; }
}
public class RootObject
{
public bool batchcomplete { get; set; }
public Query query { get; set; }
}
Now I create a C# Class to serialize my resulted Json object. I want my final Json in this way-
public class Poi
{
public string Title { set; get; }
public string Description { set; get; }
public List<PoiImage> Images { set; get; }
public string OpeningHours { set; get; }
public double AirDistanceInKm { set; get; }
public double Lon { set; get; }
public double Lat { set; get; }
}
public class PoiImage
{
public string ImageID { set; get; }
}
I am using this code to Deserialize and Seralize JSON objects. But having lot of problems which I have mentioned beside code.
Edited Code
using (WebClient client = new WebClient())
{
try
{
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&redirects=1&generator=geosearch&prop=extracts|coordinates|pageimages&ggslimit=20&ggsradius=1000&ggscoord=52.5243700|13.4105300&&formatversion=2&exintro=1&explaintext=1&exlimit=20&coprop=type|dim|globe&colimit=20&piprop=thumbnail&pithumbsize=400&pilimit=20");
var json = JsonConvert.DeserializeObject<RootObject>(response);
List<Poi> poi = new List<Poi>();
foreach (var page in json.query.pages)
{
Poi obj = new Poi();
obj.Title = page.title;
obj.Description =page.extract ;
var Image = new PoiImage();
var ImgfirstKey = page.thumbnail.source;
Image.ImageID = string.Format("{0:X}.jpg", ImgfirstKey.GetHashCode());
obj.Images = new List<PoiImage> {Image};
obj.Lat = page.coordinates.First().lat;
obj.Lon = page.coordinates.First().lon;
poi.Add(obj);
}
JsonSerializerSettings serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented };
string result= Newtonsoft.Json.JsonConvert.SerializeObject(poi, serializerSettings);
Console.WriteLine(result);
}
catch(Exception)
{
}
}
Just move the serialize code outside of the foreach
and serialize the list<poi>
foreach (page in rootObject.Query.Pages){
//do the magic
//then
poi.add(obj)
}
JsonSerializerSettings serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented };
Newtonsoft.Json.JsonConvert.SerializeObject(poi, serializerSettings);

Unable To Parse JSON Response in C#

I am trying to parse a whois json response but when I try parse it I get null values.
string html;
string whoisUrl = "https://whois.apitruck.com/:google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(whoisUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
html = reader.ReadToEnd();
}
}
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.created);
Object
class Class1
{
public string created { get; set; }
}
can anyone please point what I am doing wrong here ?
Your Class1 doesn't get the value since "created" is part of the "response" and not the root level of the JSON reponse.
You'll either need to use dynamic or create a hierarchy for the classes for a simple fix.
class Class1
{
public Response Response { get; set; }
}
class Response
{
public string created { get; set; }
}
Then you can use this:
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.Response.created);
UPDATE
Also, here's an example of how to use the dynamic:
var m = JsonConvert.DeserializeObject<dynamic>(html);
DateTime created = (DateTime)m.response.created;
There is nice app to convert json to .net class:
public class Registrar
{
public string id { get; set; }
public string name { get; set; }
public object email { get; set; }
public string url { get; set; }
}
public class Response
{
public string name { get; set; }
public string idnName { get; set; }
public List<string> status { get; set; }
public List<string> nameserver { get; set; }
public object ips { get; set; }
public string created { get; set; }
public string changed { get; set; }
public string expires { get; set; }
public bool registered { get; set; }
public bool dnssec { get; set; }
public string whoisserver { get; set; }
public List<object> contacts { get; set; }
public Registrar registrar { get; set; }
public List<string> rawdata { get; set; }
public object network { get; set; }
public object exception { get; set; }
public bool parsedContacts { get; set; }
}
public class RootObject
{
public int error { get; set; }
public Response response { get; set; }
}
...
RootObject result = JsonConvert.DeserializeObject<RootObject>(html);
var created = result.response.created;

Extract data from Json string

I got a string containing Json. It looks like this:
"status_code":200,
"status_txt":"OK",
"data":
{
"img_name":"D9Y3z.png",
"img_url":"http:\/\/s1.uploads.im\/D9Y3z.png",
"img_view":"http:\/\/uploads.im\/D9Y3z.png",
"img_width":"167",
"img_height":"288",
"img_attr":"width=\"167\" height=\"288\"",
"img_size":"36.1 KB",
"img_bytes":36981,
"thumb_url":"http:\/\/s1.uploads.im\/t\/D9Y3z.png",
"thumb_width":360,
"thumb_height":360,
"source":"http:\/\/www.google.com\/images\/srpr\/nav_logo66.png",
"resized":"0",
"delete_key":"df149b075ab68c38"
}
I am trying to get a hold of the "img_url". I have Json.NET installed and I´ve found similar questions here..
for example something like this:
JObject o = JObject.Parse("{'People':[{'Name':'Jeff'},{'Name':'Joe'}]}");
// get name token of first person and convert to a string
string name = (string)o.SelectToken("People[0].Name");
In my case I changed ("People[0].Name") to ("img_url"),("img_url[0]) etc..no luck
This is my code now:
public string tempJson { get; set; }
public ActionResult SaveUploadedFile(string test)
{
using (WebResponse wrs = wrq.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
tempJson = json;
}
}
Do I have to do something with the string before I can extract the value?
Thanks!
img_url is not a property of root object - it's a property of data object:
var obj = JObject.Parse(json);
var url = (string)obj["data"]["img_url"]; // http://s1.uploads.im/D9Y3z.png
Another option:
var url = (string)obj.SelectToken("data.img_url");
With help of this site
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.data.img_url);
public class Data
{
public string img_name { get; set; }
public string img_url { get; set; }
public string img_view { get; set; }
public string img_width { get; set; }
public string img_height { get; set; }
public string img_attr { get; set; }
public string img_size { get; set; }
public int img_bytes { get; set; }
public string thumb_url { get; set; }
public int thumb_width { get; set; }
public int thumb_height { get; set; }
public string source { get; set; }
public string resized { get; set; }
public string delete_key { get; set; }
}
public class RootObject
{
public int status_code { get; set; }
public string status_txt { get; set; }
public Data data { get; set; }
}
You can also do the same thing with the use of dynamic keyword (without declaring above classes)
dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.data.img_url);

Categories