Task and deserializing objects from api logic and deserializing json - c#

I was hoping someone could help walk me through some of this logic here. I hope this isn't too specific so that maybe it will help other people. It will definitely seem that way, I am sure, but I don't know if this is is common in industry or not (I am supposed to be an economist, but I am helping with the programming until we get someone more skilled at this trade).
The background: I was asked to deserialize a json object that is returned by the api, but I am not sure if I am understanding the code correctly so until then I won't be able to deserialize it. My two hopes are that someone can correct me if my logic is incorrect and to help me figure out how to deserialize it.
The goal is pretty simple: show a list using a UITableView of the items that are returned from the api. I have the UITableView that is all set up. I just need to fill it with the data now. Here is what was written before me. It is the task/api:
public async Task<Food> FoodCatalog(int category)
{
string url = Service.baseURL + Service.FoodCatalog + "?category=" + category.ToString();
dynamic results = await Service.getDataFromService(url).ConfigureAwait(false);
string json = results as string; // Otherwise error next line ???
Food items = JsonConvert.DeserializeObject<Food>(json);
return items;
}
Here is the Food class:
public struct FoodStruct
{
[JsonProperty(PropertyName = "FoodGroupTypeId")] public short? FoodGroupTypeId;
[JsonProperty(PropertyName = "FoodGroupDescription")] public string FoodGroupDescription;
[JsonProperty(PropertyName = "FoodId")] public int? FoodId;
[JsonProperty(PropertyName = "FoodDescription")] public string FoodDescription;
}
public class Food
{
[JsonProperty(PropertyName = "Table Selection")] public static List<FoodStruct> FoodList = new List<FoodStruct>();
public FoodStruct this[int key] { get { return FoodList[key]; } }
public static string[] ToStringArray()
{
string[] list = new string[FoodList.Count];
int i = 0;
foreach (FoodStruct fs in FoodList)
{
list[i++] = fs.FoodDescription;
}
return list;
}
public static implicit operator string(Food v)
{
throw new NotImplementedException();
}
}
The api has a task that connects to the url, gets the results, and returns the deserialized object as a class? Is that how this logic works?
The Food class looks like it does what I want it to. It looks like it creates a list of the food description (the food group, etc isn't terribly important yet). But I have no way of accessing that food list and I am really not completely sure this is doing what I want it to, but it seems that way.
Can someone correct me on the logic and help me figure out how to deserialize the object to put it in the UITableView?

Deserialize you response like below
public async Task<Food> FoodCatalog(int category)
{
string url = Service.baseURL + Service.FoodCatalog + "?category=" + category.ToString();
dynamic results = await Service.getDataFromService(url).ConfigureAwait(false);
string json = results as string; // Otherwise error next line ???
var items = JsonConvert.DeserializeObject<List<Food>>(json);
return items;
}
In your ViewController bind your UITableView
public async override void ViewDidLoad()
{
//Create your API class object & call foodCatalog method here
var items=await FoodCatalog(params)
//Bind your UITableView
mainListview.Source = new TableViewSource(items);
}
For more information about how to bind TableView visit this

You can use Newtonsoft.Json:
string foodJson = "[{\"FoodGroupTypeId\":\"apple\", \"FoodGroupDescription\":\"apple fruit\",\"FoodId\": \"Fuji Apple\",\"FoodDescription\": \"Fuji Apple\"}]";
var obj = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(foodJson);
foreach (var ch in obj.Children())
{
string id = ch["FoodGroupTypeId"].ToString();
}

Related

Get property value of object in an list

I want to get an property value from an object that is in a list and put it into textbox.text
Below i have an example of my code:
The object:
public class Incident
{
public int Incident_id { get; set; }
public string Description { get; set; }
public string Caller { get; set; }
}
Below is my code in my form class:
List<Incident> incidentById = new List<Incident>();
incidentById = db.GetIncidentById(ID);
when my list is filled i want to put the string Caller into an textbox somewhat like below:
textBoxCaller.Text = incidentById[1].Caller;
I'm stuck at this point so i hope someone can help me out.
Thanks!
EDIT:
public List<Incident> GetIncidentById(int id)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("IncidentLog")))
{
var output = connection.Query<Incident> ($"select * from Incidents where Incident_id like #id", new { id = "%id%" }).ToList();
return output;
}
}
I wasn't passing the right value into my query
this did the trick!
What you want is $"select * from Incidents where Incident_id = #id", new { id }
do you want first value should go?
check like.
if(incidentById.Count>0)
{
textBoxCaller.Text = incidentById.First().Caller;
}
// or you can join all Caller in list like
if(incidentById.Count>0)
{
textBoxCaller.Text = string.join(",",incidentById.Select(x=>x.Caller));
}
The issue that you are facing is that you are trying to access the second element in the list when there are not two or more elements in the list. If you are trying to access the first element in the list, then you could do either
textBoxCaller.Text = incidentById[0].Caller;
or
textBoxCaller.Text = incidentById.First().Caller;
If you do in fact want the second element of the list, then you should be checking to verify that it's length is at least two:
if(incidentById.Count >= 2)
{
...
}
Finally, as mentioned in a comment, you should rename GetIncidentById to something that makes clear it is returning a list, like GetIncidentsById or something similar.

Populate WPF DataGrid With JSON Data in C# using RestSharp

I would tell you I am relatively new to all of this, but it will probably be obvious shortly. I have been researching for two days without any luck in finding my specific question answered so here is what I am trying to do:
In the MainWindow code behind of a WPF app I have this class:
public class LocaleInfo
{
public string id { get; set; }
public string category { get; set; }
public bool jobSite { get; set; }
public bool singleJob { get; set; }
public bool useMasterPack { get; set; }
public string maxAllowed { get; set; }
}
Which I add a list to in order to handle JSON data coming from a web service formatted as an array. (Comments added to help you understand my line of thinking and maybe shed light on why I built each line like I did - hope it helps!)
public List<LocaleInfo> LocaleList;
I then have the following code to get the JSON data:
var client = new RestClient("https://webservice info"); // Create Rest Client
var request = new RestRequest(Method.GET); //Create Rest Request
request.RequestFormat = RestSharp.DataFormat.Json; // Request JSON to ensure accuracy
request.AddHeader("Authorization", "tokenxxx"); // Add header item Authorization and Token
var response = client.Execute(request); // Execute the Request
JsonDeserializer deserial = new JsonDeserializer(); // Create JSON Deserializer object
LocaleList = deserial.Deserialize<List<LocaleInfo>>(response); // Deserialize JSON Receieved from API/WEbservice into List<class>
Int32 totalCount = LocaleList.Count; // Create variable and get total record count
txtCount.Text = totalCount.ToString(); // Show record count
I believe it populates the list as I get a proper count.
On the MainWindow.xaml I have placed a DataGrid with 6 columns with headers. What I cannot seem to find or figure out is how to link or iterate through the list to add the data into the DataGrid.
Someday I will look back on this post and probably shake my head, but this is where I am at and I could really use some help.
Thanks so much in advance!
Add this in your MainWindow's Constructor :
DataContext = this;
then use ObservableCollection instead of List :
Public ObservableCollection<LocalInfo> LocalList{get; set;}

Process XML output from API

I am getting an XML return from an Ebay API call. This is actually an Ebay category list of collections. But the problem is, I can't access its collection from XML output. I have attached two pictures - the first one showing debug of XML value returning variable, and the second one showing "InnerList". My main goal is prepare this XML data to store on my database, so I need a clean list of values from XML data. Any ideas?
You could deserialize your xml into your own class/object - Then it might be easier to work with. All i do is put xml tags to a class and i can deserialize it. See the class and method below:
public static T Deserialize<T>(string xmlText)
{
try
{
var stringReader = new System.IO.StringReader(xmlText);
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
catch
{
throw;
}
}
[XmlElement("adress")]
public class Adress
{
[XmlElementAttribute("street_address")]
public string street_address { get; set; }
[XmlElementAttribute("postal_code")]
public string postal_code { get; set; }
[XmlElementAttribute("city")]
public string city { get; set; }
[XmlElementAttribute("country")]
public string country { get; set; }
}
public main()
{
Adress myAdress = Deserialize<Adress>(XMLstring);
}
Hope it helps!
It seems you are using Ebay SDK. Please try code below to process return values.
foreach (CategoryTypeCollection item in categories)
{
item.ItemAt(0).CategoryID = "This is how you access the properties of he returned result";
// THE XML is already parsed for you via SDK, so you don't have to parse it...
// since i wrote foreach loop here, always access itemAt 0th index posiiton
}

Can't get data from deserialized Json string

I am really confused as to why I can't access any data that I have deserialized from Json string. When I step through the process I can see that the data is there, I just can't access it.
I am placing the data into Dictionary<string, object>, it's Count is 2. It contains object{object[]} (which I read as an ArrayList of objects?), and an object with response information.
I'm not too fussed about the response information I need to access the objects in the ArrayList. I'm having no such luck, my code is below:
var output = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(await response.Content.ReadAsStringAsync());
I have tried to get just the ArrayList using output["List"] (List is the objects key) and can still see all of the objects inside but still can't access them. It's probably a simple fix, it always is, but I have been staring at this problem all day and just can't make sense of it so could do with another pair of eyes.
Thanks
EDIT
The Json string is in the following format:
{"List":[{"Id":1,"intProperty":2,"boolProperty":false},{"Id":2,"intProperty":3,"boolProperty":false},{"Id":4,"intProperty":5,"boolProperty":false}],"ResponseInformation":{Other info here}}
Deserialize it into a class:
public class ListClass
{
public int Id;
public int IntProperty;
public bool boolProperty;
}
and then
var output = new JavaScriptSerializer().Deserialize<Dictionary<string, ListClass>>(await response.Content.ReadAsStringAsync());
And that should work!
I have figured out a long winded way of getting the information I need, If anyone can see a way to condense the code I'm open to suggestions :)
First I created my Currency class
public class Currency
{
public int CurrencyId { get; set; }
public int GlobalCurrencyId { get; set; }
public bool Archived { get; set; }
}
Next I deserialized my Json as I did in my question
var output = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(await response.Content.ReadAsStringAsync());
Next is the long winded bit; I used a foreach statement to get each element of my output variable. It was then made clear that the data inside was an array of dictionary objects so I created a list of Currency class objects:
var currencyObject = output["List"];
List<Currency> currencyList = new List<Currency>();
Currency item;
ArrayList myList = currencyObject as ArrayList;
foreach (object element in myList)
{
Dictionary<string, object> L1 = element as Dictionary<string, object>;
item = new Currency();
item.CurrencyId = Convert.ToInt32(L1["CurrencyId"]);
item.GlobalCurrencyId = Convert.ToInt32(L1["GlobalCurrencyId"]);
item.Archived = Convert.ToBoolean(L1["Archived"]);
currencyList.Add(item);
}
Figured it out in just two lines!!
var json = response.Content.ReadAsStringAsync().Result;
IList<Currency> output = new JsonSerializer().Deserialize<IList<Currency>>(new JsonTextReader(new StringReader(json)));

c# -> javascript, Json decoding misses property

I have a c# object (below) that I'm trying to send to my javascript.
My problem is, that while I can iterate over the items in the list, I can't get to the string-property ('Period').
Referencing the object in JS shows no property at all. After Json-encoding in c#, I can still see the property just before returning it to caller (hovering over the result variable in below function):
[OutputCache(Duration = 0, VaryByParam = "None")]
public JsonResult GetRankingList() {
Response.ContentType = "text/javascript";
var user = _userService.GetUserByPrincipal(User);
// Note, we do this while the user waits as we need to make progress in repeated calls to get the compared ranking list.
_businessLogicServiceMaintenance.PerformMaintenanceSteps();
//TODO: Replace with userid (Guid)
var rankingList = _presenterService.GetRankingListForDisplay(user);
if (rankingList == null)
return Json("");
var result = Json(rankingList);
return result;
}
How on earth can I get past this? Any comments appreciated!
Yours, Anders, Denmark,
public class RankingListForDisplay : List<RankingListLine>
{
public string Period { get; set; }
}
Thanks for taking your time - I found a solution.
I changed above implementation of RankingListForDisplay to the one below. For some reason json likes it way better ;-)
public class RankingListForDisplay
{
public List<RankingListLine> Lines { get; set; }
public string Period { get; set; }
public RankingListForDisplay()
{
Lines = new List<RankingListLine>();
Period = "<Unspecified>";
}
}

Categories

Resources