Fetching data from Json and displaying it in Combobox - c#

I am trying to get a json file using a url and deserialize the json and display a particular field in the combobox but nothing shows up
WebClient client = new WebClient();
string json =
client.DownloadString("https://restcountries.eu/rest/v2/all/");
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer deserializer = new
DataContractJsonSerializer(typeof(RootObject));
RootObject obj = (RootObject)deserializer.ReadObject(ms);
foreach (var name in obj.name)
{
comboBox1.Items.Add(obj.name);
}
}
this is the POCO class
public class RootObject
{
public string name { get; set; }
public List<string> topLevelDomain { get; set; }
public string alpha2Code { get; set; }
public string alpha3Code { get; set; }
public List<string> callingCodes { get; set; }
public string capital { get; set; }
public List<object> altSpellings { get; set; }
public string region { get; set; }
public string subregion { get; set; }
public int population { get; set; }
public List<object> latlng { get; set; }
public string demonym { get; set; }
public double? area { get; set; }
public double? gini { get; set; }
public List<string> timezones { get; set; }
public List<object> borders { get; set; }
public string nativeName { get; set; }
public string numericCode { get; set; }
public List<Currency> currencies { get; set; }
public List<Language> languages { get; set; }
public Translations translations { get; set; }
public string flag { get; set; }
public List<object> regionalBlocs { get; set; }
public string cioc { get; set; }
}
I want to display the name in the combobox
here is the link to the json
https://restcountries.eu/rest/v2/all/

You was trying deserialized one result, however result are list.
WebClient client = new WebClient();
string json =
client.DownloadString("https://restcountries.eu/rest/v2/all/");
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer deserializer = new
DataContractJsonSerializer(List<RootObject>); //TODO: FIXED
List<RootObject>obj = (List<RootObject>)deserializer.ReadObject(ms); //TODO: FIXED
foreach (var name in obj.name)
{
comboBox1.Items.Add(obj.name);
}
}
it´s work

Add manage nuget package : Newtonsoft.Json
WebClient client = new WebClient();
string json =
client.DownloadString("https://restcountries.eu/rest/v2/all/");
dynamic dyn = JsonConvert.DeserializeObject<List<CountryName>>(json);
foreach (var item in dyn)
{
comboBox1.Items.Add(item.name);
}
public class CountryName
{
public string name { get; set; }
}
Best and fast approach and it's working fine

#A.M.Patel
i couldn't able to post it in the comment section
the code u sent worked perfectly
i too used newtonsoft.json
if iam not annoying you
can u spot out my mistakes in my code
1st code which i tried for single entry
HttpClient http = new HttpClient();
string url = "https://restcountries.eu/rest/v2/alpha/ind";
HttpResponseMessage response = http.GetAsync(new Uri(url)).Result;
string responseBody = response.Content.ReadAsStringAsync().Result;
var countries = JsonConvert.DeserializeObject(responseBody);
var details = JObject.Parse(countries.ToString());
comboBox1.Items.Add(countrynames);
it worked well
2nd code which i tried for multiple entries it doesn't showed any values in the combobox the combobox remained empty
HttpClient http = new HttpClient();
IDictionary<String, Int32> countrycounts = new Dictionary<String, Int32>();
string url = "https://restcountries.eu/rest/v2/all/";
HttpResponseMessage response = http.GetAsync(new Uri(url)).Result;
string responseBody = response.Content.ReadAsStringAsync().Result;
var countries = JsonConvert.DeserializeObject(responseBody);
var details = JObject.Parse(countries.ToString());
foreach (var obj in details){
string countrynames = details["name"].ToString();
if (countrycounts.ContainsKey(countrynames))
{
int count = countrycounts[countrynames];
count++;
countrycounts[countrynames] = count;
comboBox1.Items.Add(countrynames);
}
else { comboBox1.Items.Add(countrynames); }

Related

Deserialize XML classes to one class for writing to database

I am trying to deserialize XML and save the results to a database using entity framework.
The first section of code is just to get the needed xml file from an API.
Please see below:
public static void Main()
{
Program semoAPI = new Program();
using (WebClient webClient = new WebClient())
{
WebClient n = new WebClient();
//Bid Ask Curves
var bidAskCurves = n.DownloadString("https://reports.semopx.com/api/v1/documents/static-reports?" +
"page=1&page_size=1&order_by=ASC&ReportName=Bid/Ask%20Curves&Group=Market%20Data");
semoReports = JsonConvert.DeserializeObject<SemoReports>(bidAskCurves);
Console.WriteLine("Bid Ask Curves Report: ");
Console.WriteLine(semoReports.ResourceBaseUri + "/" + semoReports.Items[0].ResourceName);
string bidAskCurvesXML = semoReports.ResourceBaseUri + "/" + semoReports.Items[0].ResourceName;
XDocument bacDoc = XDocument.Load(bidAskCurvesXML);
//Execute DeserializeBidAskCurves
semoAPI.DeserializeBidAskCurves(bidAskCurvesXML);
}
}
Below is how my class is setup which contains the XML Elements I need:
namespace SEMO_app
{
[XmlRoot("BidAskCurves")]
public class BidAskCurves
{
[Key]
public int ReportID { get; set; }
[XmlElement("MarketArea")]
public MarketArea[] MarketAreas{ get; set; }
}
public class MarketArea
{
public string MarketAreaName { get; set; }
[XmlElement("DeliveryDay")]
public DeliveryDay[] DeliveryDays { get; set; }
}
public class DeliveryDay
{
public string Day { get; set; }
[XmlElement("TimeStep")]
public TimeStep[] TimeSteps{ get; set; }
}
public class TimeStep
{
public string TimeStepID { get; set; }
[XmlElement("Purchase")]
public Purchase[] Purchases { get; set; }
}
public class Purchase
{
public string Price { get; set; }
public string Volume { get; set; }
}
}
From here i would like to deserialize the XML and save the information to a database, below is the code I have so far which deserialize's the XML and gives the results back fine in the console.writesection.
However I am unable to save these values to the database table. The code complies and executes fine and a the database table updates, however the table only contains a report id column. Where I would like it to contain the items listed in the console.write section.
private void DeserializeBidAskCurves(string filename)
{
//Visual only not needed
Console.WriteLine("\n" + "Reading BidAskCurves XML File");
Console.WriteLine("===========================================================");
// Create an instance of the XmlSerializer.
XmlSerializer serializer = new XmlSerializer(typeof(BidAskCurves));
// Declare an object variable of the type to be deserialized.
BidAskCurves item;
using (XmlReader reader = XmlReader.Create(filename))
{
// Call the Deserialize method to restore the object's state.
item = (BidAskCurves)serializer.Deserialize(reader);
//Write out the properties of the object. (Visual Only, not needed)
Console.Write(
item.MarketAreas[0].MarketAreaName + "\t" +
item.MarketAreas[0].DeliveryDays[0].Day + "\t" +
item.MarketAreas[0].DeliveryDays[0].TimeSteps[0].TimeStepID + "\t" +
item.MarketAreas[0].DeliveryDays[0].TimeSteps[0].Purchases[0].Price + "\t" +
item.MarketAreas[0].DeliveryDays[0].TimeSteps[0].Purchases[0].Volume);
//write the properties to the db
using (SEMOContext context = new SEMOContext())
{
context.BidAskCurvesReports.Add(item);
context.SaveChanges();
}
}
}
Link to xml file: https://reports.semopx.com/documents/BidAskCurves_NI-IDA3_20190401_20190401161933.xml
Thanks for any help in advance.
Initially, it's hard to know what's the problem actually is?
But after visiting URI generated by
string bidAskCurvesXML = semoReports.ResourceBaseUri + "/" + semoReports.Items[0].ResourceName;
And that is https://reports.semopx.com/documents/BidAskCurves_NI-IDA3_20190401_20190401161933.xml
So, The class structure that you are using is different than xml generated by URI.
You need to use below class structure for your xml
[XmlRoot("Purchase")]
public class Purchase
{
[XmlElement("Price")]
public string Price { get; set; }
[XmlElement("Volume")]
public string Volume { get; set; }
}
[XmlRoot("Sell")]
public class Sell
{
[XmlElement("Price")]
public string Price { get; set; }
[XmlElement("Volume")]
public string Volume { get; set; }
}
[XmlRoot("TimeStep")]
public class TimeStep
{
[XmlElement("TimeStepID")]
public string TimeStepID { get; set; }
[XmlElement("Purchase")]
public List<Purchase> Purchase { get; set; }
[XmlElement("Sell")]
public List<Sell> Sell { get; set; }
}
[XmlRoot("DeliveryDay")]
public class DeliveryDay
{
[XmlElement("Day")]
public string Day { get; set; }
[XmlElement("TimeStep")]
public List<TimeStep> TimeStep { get; set; }
}
[XmlRoot("MarketArea")]
public class MarketArea
{
[XmlElement("MarketAreaName")]
public string MarketAreaName { get; set; }
[XmlElement("DeliveryDay")]
public DeliveryDay DeliveryDay { get; set; }
}
[XmlRoot("BidAskCurves")]
public class BidAskCurves
{
[XmlElement("MarketArea")]
public MarketArea MarketArea { get; set; }
}
And after using above class structure with XmlSerializer there are total 12 timestamp available
Usage:
XmlSerializer serializer = new XmlSerializer(typeof(BidAskCurves));
BidAskCurves item;
using (XmlReader reader = XmlReader.Create("https://reports.semopx.com/documents/BidAskCurves_NI-IDA3_20190401_20190401161933.xml"))
{
item = (BidAskCurves)serializer.Deserialize(reader);
//Your code to add above parsed data into database.
}
Output: (From Debugger)
Edit1:
To add first purchase's volume and price and sell's volume and price then,
...
item = (BidAskCurves)serializer.Deserialize(reader);
foreach (var ts in item.MarketArea.DeliveryDay.TimeStep)
{
BidAskCurvesData bidAskCurvesData = new BidAskCurvesData
{
ReportID = 123,
MarketAreaName = item.MarketArea.MarketAreaName,
Day = item.MarketArea.DeliveryDay.Day,
TimeSetID = ts.TimeStepID,
PurchasePrice = ts.Purchase[0].Price,
PurchaseVolume = ts.Purchase[0].Volume,
SellPrice = ts.Sell[0].Price,
SellVolume = ts.Sell[0].Volume
};
using (SEMOContext context = new SEMOContext())
{
context.BidAskCurvesReports.Add(item);
context.SaveChanges();
}
}
static void Main(string[] args)
{
using (WebClient webClient = new WebClient())
{
//Bid Ask Curves
var bidAskCurves = webClient.DownloadString("https://reports.semopx.com/documents/BidAskCurves_NI-IDA3_20190401_20190401161933.xml");
var serializer = new XmlSerializer(typeof(BidAskCurves));
BidAskCurves result;
using (TextReader reader = new StringReader(bidAskCurves))
{
// here it is
result = (BidAskCurves)serializer.Deserialize(reader);
}
}
Console.ReadKey();
}
and xml objects:
[XmlRoot(ElementName = "Purchase")]
public class Purchase
{
[XmlElement(ElementName = "Price")]
public string Price { get; set; }
[XmlElement(ElementName = "Volume")]
public string Volume { get; set; }
}
[XmlRoot(ElementName = "Sell")]
public class Sell
{
[XmlElement(ElementName = "Price")]
public string Price { get; set; }
[XmlElement(ElementName = "Volume")]
public string Volume { get; set; }
}
[XmlRoot(ElementName = "TimeStep")]
public class TimeStep
{
[XmlElement(ElementName = "TimeStepID")]
public string TimeStepID { get; set; }
[XmlElement(ElementName = "Purchase")]
public List<Purchase> Purchase { get; set; }
[XmlElement(ElementName = "Sell")]
public List<Sell> Sell { get; set; }
}
[XmlRoot(ElementName = "DeliveryDay")]
public class DeliveryDay
{
[XmlElement(ElementName = "Day")]
public string Day { get; set; }
[XmlElement(ElementName = "TimeStep")]
public List<TimeStep> TimeStep { get; set; }
}
[XmlRoot(ElementName = "MarketArea")]
public class MarketArea
{
[XmlElement(ElementName = "MarketAreaName")]
public string MarketAreaName { get; set; }
[XmlElement(ElementName = "DeliveryDay")]
public DeliveryDay DeliveryDays { get; set; }
}
[XmlRoot(ElementName = "BidAskCurves")]
public class BidAskCurves
{
[XmlElement(ElementName = "MarketArea")]
public MarketArea MarketAreas { get; set; }
}
EDIT
loop over the result:
foreach (var item in deliveryDays.TimeStep)
{
// var day = deliveryDays.Day
var timeStep_Purchase = item.Purchase;
var timeStep_Sell = item.Sell;
var timeStep_Id = item.TimeStepID;
}

Paste text from EditText to xml string

I have EditText field and WebClient.
In EditText user write city.
EditText misto = FindViewById<EditText>(Resource.Id.misto) ;
TextView one = FindViewById<TextView>(Resource.Id.parentContainer);
TextView two = FindViewById<TextView>(Resource.Id.clicklistener1);
TextView three = FindViewById<TextView>(Resource.Id.clicklistener2);
TextView four = FindViewById<TextView>(Resource.Id.clicklistener3);
misto.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => {
var city = e.Text.ToString ();
};
I need to place text from EditText to xml string.
Code of POST request with xml
nadislati.Click += delegate
{
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["Order"] = "<Order \n CallConfirm=\"1\"\n PayMethod=\"Безнал\" \n QtyPerson=\"2\" \n Type=\"2\" \n PayStateID=\"0\" \n Remark=\"тестовый заказ с мобильного приложения. просьба при получении заказа переслать скриншот на имейл ....#\" \n RemarkMoney=\"0\" \n TimePlan=\"\" \n Brand=\"1\" \n DiscountPercent=\"0\" \n BonusAmount=\"0\"\n Department=\"\"\n >\n <Customer Login=\"suhomlineugene#gmail.com\" FIO=\"Evgenyi Sukhomlin\"/>\n <Address \n CityName=\"\" \n StationName=\"\" \n StreetName=\"\" \n House=\"\" \n Corpus=\"\" \n Building=\"\" \n Flat=\"\" \n Porch=\"\" \n Floor=\"\" \n DoorCode=\"\"\n />\n\n <Phone Code=\" 096\" Number=\"50 526-43-19\" />\n <Products>\n <Product Code=\"574\" Qty=\"1\" />\n </Products>\n </Order>";
values["OrderText"] = "hello";
var response = client.UploadValues("http://193.203.48.54:5000/fastoperator.asmx/AddOrder", values);
var responseString = Encoding.UTF8.GetString(response);
}
Vibrator vib = (Vibrator)this.GetSystemService(Context.VibratorService);
vib.Vibrate(30);
var intent31 = new Intent(this, typeof(Cart3Activity));
StartActivity(intent31);
};
How I can realize this?
Normally you would have a data contract (a set of classes which represent the XML). You then populate this data contract with values. When you are done and want to send it as XML to the server, you take that object and serialize it into XML or JSON or whatever format the service requires. Taking the XML you have shown in the Order and throwing it through a XML 2 C# generator you get this:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="Customer")]
public class Customer {
[XmlAttribute(AttributeName="Login")]
public string Login { get; set; }
[XmlAttribute(AttributeName="FIO")]
public string FIO { get; set; }
}
[XmlRoot(ElementName="Address")]
public class Address {
[XmlAttribute(AttributeName="CityName")]
public string CityName { get; set; }
[XmlAttribute(AttributeName="StationName")]
public string StationName { get; set; }
[XmlAttribute(AttributeName="StreetName")]
public string StreetName { get; set; }
[XmlAttribute(AttributeName="House")]
public string House { get; set; }
[XmlAttribute(AttributeName="Corpus")]
public string Corpus { get; set; }
[XmlAttribute(AttributeName="Building")]
public string Building { get; set; }
[XmlAttribute(AttributeName="Flat")]
public string Flat { get; set; }
[XmlAttribute(AttributeName="Porch")]
public string Porch { get; set; }
[XmlAttribute(AttributeName="Floor")]
public string Floor { get; set; }
[XmlAttribute(AttributeName="DoorCode")]
public string DoorCode { get; set; }
}
[XmlRoot(ElementName="Phone")]
public class Phone {
[XmlAttribute(AttributeName="Code")]
public string Code { get; set; }
[XmlAttribute(AttributeName="Number")]
public string Number { get; set; }
}
[XmlRoot(ElementName="Product")]
public class Product {
[XmlAttribute(AttributeName="Code")]
public string Code { get; set; }
[XmlAttribute(AttributeName="Qty")]
public string Qty { get; set; }
}
[XmlRoot(ElementName="Products")]
public class Products {
[XmlElement(ElementName="Product")]
public Product Product { get; set; }
}
[XmlRoot(ElementName="Order")]
public class Order {
[XmlElement(ElementName="Customer")]
public Customer Customer { get; set; }
[XmlElement(ElementName="Address")]
public Address Address { get; set; }
[XmlElement(ElementName="Phone")]
public Phone Phone { get; set; }
[XmlElement(ElementName="Products")]
public Products Products { get; set; }
[XmlAttribute(AttributeName="CallConfirm")]
public string CallConfirm { get; set; }
[XmlAttribute(AttributeName="PayMethod")]
public string PayMethod { get; set; }
[XmlAttribute(AttributeName="QtyPerson")]
public string QtyPerson { get; set; }
[XmlAttribute(AttributeName="Type")]
public string Type { get; set; }
[XmlAttribute(AttributeName="PayStateID")]
public string PayStateID { get; set; }
[XmlAttribute(AttributeName="Remark")]
public string Remark { get; set; }
[XmlAttribute(AttributeName="RemarkMoney")]
public string RemarkMoney { get; set; }
[XmlAttribute(AttributeName="TimePlan")]
public string TimePlan { get; set; }
[XmlAttribute(AttributeName="Brand")]
public string Brand { get; set; }
[XmlAttribute(AttributeName="DiscountPercent")]
public string DiscountPercent { get; set; }
[XmlAttribute(AttributeName="BonusAmount")]
public string BonusAmount { get; set; }
[XmlAttribute(AttributeName="Department")]
public string Department { get; set; }
}
}
You probably need to fix some of the types on some of the properties as the generator is not super clever about this.
Anyways, populate those properties with your values and when you want to create XML from it:
public static string SerializeObject<T>(this T toSerialize)
{
var xmlSerializer = new XmlSerializer(toSerialize.GetType());
using(var textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
var myXml = SerializeObject<Order>(order);
Where order is an instance of Order. myXml will be your XML string you can pass on to the server.
EDIT
Since you already have that XML string, you will need to deserialize it into the object, so you can manipulate it:
public static T DeserializeObject<T>(string xml)
{
using (var ms = new MemoryStream())
using (var writer = new StreamWriter(ms))
{
writer.Write(xml);
ms.Position = 0;
var serializer = new XmlSerializer(typeof(T));
using (var reader = XmlReader.Create(ms))
return (T)serializer.Deserialize(reader);
}
}
var order = DeserializeObject<Order>(xmlOrder);
Then you can manipulate order and when you are done, convert it back to XML with:
var myXml = SerializeObject<Order>(order);
You have to make sure your XML is well formed when you use these methods.

Read Json from file and display [duplicate]

This question already has answers here:
Android app Json
(2 answers)
Closed 7 years ago.
I writing android app and have API
Writing API to file like this
Code of writing:
string url2 = "http://new.murakami.ua/?mkapi=getProducts";
JsonValue json = await FetchAsync(url2);
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine(path, "myfile.txt");
using (var streamWriter = new StreamWriter(filename, true))
{
streamWriter.Write(json.ToString());
streamWriter.Close();
}
ParseAndDisplay1(json);
ParseAndDisplay2(json);
ParseAndDisplay3(json);
ParseAndDisplay4(json);
ParseAndDisplay5(json);
ParseAndDisplay6(json);
ParseAndDisplay7(json);
ParseAndDisplay8(json);
}
private async Task<JsonValue> FetchAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//dynamic data = JObject.Parse(jsonDoc[15].ToString);
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
}
And I need to read some fields from file
I try to do it like this but it didn't work
Code:
private void ParseAndDisplay1(JsonValue json)
{
TextView productname = FindViewById<TextView> (Resource.Id.posttittle);
TextView price = FindViewById<TextView> (Resource.Id.price);
TextView weight = FindViewById<TextView> (Resource.Id.weight);
productname.Click += delegate {
var intent404 = new Intent (this, typeof(SoupesDetailActivity1));
StartActivity (intent404);
};
string path = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine (path, "myfile.txt");
using (var streamReader = new StreamReader (filename, true)) {
JsonValue firstitem = json [81];
productname.Text = firstitem ["post_title"];
price.Text = firstitem ["price"] + " грн";
weight.Text = firstitem ["weight"] + "г";
}
}
Can you help me with this problem?
Here's a simple way to read the JSON and manipulate it using Json.NET that you can install from Xamarin:
var url = "http://new.murakami.ua/?mkapi=getProducts";
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// Since you're just downloading the json you can use a webclient
using (var wc = new WebClient())
{
// Download the json data
var jsonData = await wc.DownloadStringTaskAsync(new Uri(url));
// Save the json data
File.WriteAllText(Path.Combine(path, "myfile.txt"), jsonData);
// Deserialize the Json into a list of object of the type YourObject
List<YourObject> list = JsonConvert.DeserializeObject<List<YourObject>>(jsonData);
// Do whatever you want to do with the data
foreach (var yourObject in list)
{
// this is just an example
Console.WriteLine(yourObject.post_title);
}
}
And this is the definition of the YourObject class:
// this will hold the deserialized objects and make it easy to use
// You can delete properties you don't need
public class YourObject
{
public int ID { get; set; }
public string post_author { get; set; }
public string post_date { get; set; }
public string post_date_gmt { get; set; }
public string post_content { get; set; }
public string post_title { get; set; }
public string post_excerpt { get; set; }
public string post_status { get; set; }
public string comment_status { get; set; }
public string ping_status { get; set; }
public string post_password { get; set; }
public string post_name { get; set; }
public string to_ping { get; set; }
public string pinged { get; set; }
public string post_modified { get; set; }
public string post_modified_gmt { get; set; }
public string post_content_filtered { get; set; }
public int post_parent { get; set; }
public string guid { get; set; }
public int menu_order { get; set; }
public string post_type { get; set; }
public string post_mime_type { get; set; }
public string comment_count { get; set; }
public string filter { get; set; }
public object img_url { get; set; }
public string visibility { get; set; }
public string price { get; set; }
public string weight { get; set; }
public string energy { get; set; }
public string sku { get; set; }
public int category { get; set; }
}

PostAsJson not serializing correctly?

I am attempting to use a PostAsJsonAsync call to POST a model to a RESTful API and serialize the return into an object. This seems trivial as I've done this plenty times before, but I can not figure out why this is not serializing correctly. Below I have included the C# Model, JSON Response and what it is serialized into it. I've also included my code. Any help would be greatly appreciated. I should point out that the main inconsistency is with the Errors field.
C# Model:
public class AccountModel
{
public int UniqueId { get; set; }
public string Email { get; set; }
public string UserId { get; set; }
public string SingleSignOnId { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public int CompanyId { get; set; }
public string EmployeeId { get; set; }
public string Miscellaneous { get; set; }
public bool Disabled { get; set; }
public int UserTypeId { get; set; }
public Dictionary<string, List<string>> Errors { get; set; }
}
JSON Response:
{
"Errors":{
"Password":[
"Password must meet 3 category requirements"
],
"Account":[
"There was an error while creating a user."
]
},
"UniqueId":0,
"Email":"email#email.com",
"Password":"",
"UserId":null,
"SingleSignOnId":null,
"FirstName":"First",
"LastName":"Last",
"Phone":null,
"CompanyId":8888,
"UserTypeId":4455668,
"EmployeeId":null,
"Disabled":false,
"Miscellaneous":null,
}
Model serialized:
Code:
public AccountModel Create(string sessionKey, AccountModel accountModel)
{
//Send Payload
var req = new HttpClient();
req.BaseAddress = new Uri(endpoint + "/Create");
req.DefaultRequestHeaders.Accept.Clear();
req.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
req.DefaultRequestHeaders.Add(Headers.SessionKey, sessionKey);
var request = req.PostAsJsonAsync(endpoint + "/Create", accountModel);
if (request.Result.IsSuccessStatusCode)
{
var data = request.Result.Content.ReadAsStringAsync().Result;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccountModel));
return (AccountModel)serializer.ReadObject(request.Result.Content.ReadAsStreamAsync().Result);
}
else
{
throw new Exception(request.Result.Content.ReadAsStringAsync().Result);
}
}
This might be an issue with DataContractJsonSerializer. I was able to use JsonSerializer from Json.net library to deserialize the string correctly.
EDIT:
If you are using DataContractJsonSerializer, you need to provide custom settings to deserialize dictionary
DataContractJsonSerializerSettings settings =
new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccountModel), settings);
This solution is only applicable if you are using .Net 4.5+. You can always try using NewtonSoft.Json

JavaScriptSerializer, Parsing Json from HttpRequest, put pars into a table to be displayed

I made a call to a web server called Sample ApI. I want to be able to parse that data that's in json or xml, either would be nice and display it in a table format. This is what I have so far.
All I want is to be able to parse the data that's in this string _responseAsString and display a table. I don't know how to start it, I just know JavaScriptSerialzer parseXXX = new Java...lizer(). Please help me or assist in the right direction.
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_acknowledged { get; set; }
}
public ActionResult GetEvent()
{
try
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
System.IO.StreamReader _readResponse=new System.IO.StreamReader(response.GetResponseStream());
//The encrypted dynamics response in either xml or json
string _responseAsString=_readResponse.ReadToEnd();
JavaScriptSerializer parseResponse = new JavaScriptSerializer();
List<Event> events = parseResponse.Deserialize<List<Event>>(_responseAsString);
// this below is to make sure i was receiving my json data.
return Content(_responseAsString);
_readResponse.Close();
}
catch (Exception e)
{
//log error
}
return View();
}
This is the json data I receive when I make the http request:
"[{\"event_key\":\"cc2a1802-2b04-4530-ad50-0d4f0ed19dd3\",\"user_token\":\"40e62a11-40c4-408d-8cdd-1293cbaf9a41\",\"event_set_key\":\"615017f2-ae28-4b8d-9def-cf043642b928\",\"event_type\":\"Arrival\",\"event_date\":\"6/20/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"50fc1c22-d77b-4a91-b31d-da036827060b\",\"event_location_name\":\"Store2\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"True\"},{\"event_key\":\"2ac9e25e-137c-4a72-8cc5-157d67ea66c1\",\"user_token\":\"58cb4fcd-e140-4232-88c9-06eecb95b63d\",\"event_set_key\":\"00710ca7-f5d7-4c7a-bbfb-95491ae278ef\",\"event_type\":\"Arrival\",\"event_date\":\"9/23/2011
4:15:28
PM\",\"event_amount\":\"45\",\"event_location_key\":\"5a732dd5-9459-4cdd-a980-f3daf1a07343\",\"event_location_name\":\"Store4\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"},{\"event_key\":\"386b1fa1-11b2-48d9-b7f1-4bbe21ced487\",\"user_token\":\"c3d8b7ff-d85f-42a8-98f6-e091b48c2280\",\"event_set_key\":\"dc55843b-f8cf-4e8a-9091-188ce0609fe1\",\"event_type\":\"Arrival\",\"event_date\":\"9/18/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"be6d4fb4-c0e3-4303-b70d-7a22b721aa56\",\"event_location_name\":\"Store1\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"}]"
The JSON website has some good information on this.
For older browsers, you would eval the string (with some brackets to make it work):
var myObject = eval('(' + myJsonText + ')');
And these days, we tend to use
JSON.parse(myJsonText);
And server side, in C#
var serializer = new JavaScriptSerializer();
T obj = serializer.Deserialize<T>(myJsonText);
First of all...
If you're just passing through the JSON message returned from some other API, why not just return their response string verbatim (in other words, why deserialize it at all)?
public ActionResult GetEvent()
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
using (var readResponse= new StreamReader(response.GetResponseStream()))
{
return Content(readResponse.ReadToEnd(), "application/json");
}
}
Then read on
It's possible to use a JSON text reader to break apart the JSON message into a table of name/value pairs, but I think that's missing the point in your case. If the message is constant, just create a class that represents each element in the JSON message and parse it. I used json2csharp to stub such a class:
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_location_lat { get; set; }
public string event_location_long { get; set; }
public string event_description { get; set; }
public string event_acknowledged { get; set; }
}
Then use your favorite JSON serializer to deserialize into a list of these objects:
var serializer = new JavaScriptSerializer();
var events = serializer.Deserialize<List<Event>>(responseAsString);
(I prefer JSON.NET, here's the equivalent to the block above)
var events = JsonConvert.DeserializeObject<List<Event>>(responseAsString);
If you actually do need to be able to read a stream of text and generically create a table of name/value pairs, I'd use JSON.NET's LINQ-to-JSON or the JsonTextReader.

Categories

Resources