I am use api use variable date whene date change the object name change like this if i have to get data of this day i use this :https://api.covid19tracking.narrativa.com/api/2020-11-05/country/us
and the result of json object is like this :
and if i have to choose other date i change the date and the variable of date object is change like this if i have to get data of 2020-10-11 ,i calll this:
https://api.covid19tracking.narrativa.com/api/2020-11-05/country/us , and this is image show the result and the change of object date
the problem is if i deserialize the api i get result from , metadata object ,total object , updated_at , and dates object and the other object date and countries give me this error
:NullReferenceException: Object reference not set to an instance of an object
I use https://json2csharp.com/ to get class from json and this is my code :
var client = new RestClient("https://api.covid19tracking.narrativa.com/api/2020-11-05/country/us");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
// request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
Root response = client.Execute<Root>(request)?.Data;
var paystoday_confirmed = response?.dates.date.countries.US.today_confirmed;
if (paystoday_confirmed != null)
{
Debug.Log("Confirmed :" + paystoday_confirmed);
}
and this is my object's
public class Link
{
public string href { get; set; }
public string rel { get; set; }
public string type { get; set; }
}
public class Link2
{
public string href { get; set; }
public string rel { get; set; }
public string type { get; set; }
}
public class SubRegion
{
public string date { get; set; }
public string id { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_recovered { get; set; }
public int today_recovered { get; set; }
public double? today_vs_yesterday_confirmed { get; set; }
public double? today_vs_yesterday_deaths { get; set; }
public object today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_recovered { get; set; }
}
public class Region
{
public string date { get; set; }
public string id { get; set; }
public List<Link2> links { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public string source { get; set; }
public List<SubRegion> sub_regions { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_new_tests { get; set; }
public int today_new_total_hospitalised_patients { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public int today_tests { get; set; }
public int today_total_hospitalised_patients { get; set; }
public double? today_vs_yesterday_confirmed { get; set; }
public double? today_vs_yesterday_deaths { get; set; }
public double today_vs_yesterday_open_cases { get; set; }
public double? today_vs_yesterday_recovered { get; set; }
public double today_vs_yesterday_tests { get; set; }
public double? today_vs_yesterday_total_hospitalised_patients { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
public int yesterday_tests { get; set; }
public int yesterday_total_hospitalised_patients { get; set; }
}
public class US
{
public string date { get; set; }
public string id { get; set; }
public List<Link> links { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public List<Region> regions { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public double today_vs_yesterday_confirmed { get; set; }
public double today_vs_yesterday_deaths { get; set; }
public double today_vs_yesterday_open_cases { get; set; }
public double today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
}
public class Countries
{
public US US { get; set; }
}
public class Info
{
public string date { get; set; }
public string date_generation { get; set; }
public string yesterday { get; set; }
}
public class _20201102
{
public Countries countries { get; set; }
public Info info { get; set; }
}
public class Dates
{
[JsonProperty("2020-11-02")]
public _20201102 date { get; set; }
}
public class Metadata
{
public string by { get; set; }
public List<string> url { get; set; }
}
public class Total
{
public string date { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public string rid { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public double today_vs_yesterday_confirmed { get; set; }
public double today_vs_yesterday_deaths { get; set; }
public double today_vs_yesterday_open_cases { get; set; }
public double today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
}
public class Root
{
public Dates dates { get; set; }
public Metadata metadata { get; set; }
public Total total { get; set; }
public string updated_at { get; set; }
}
And this is the error on unity
It will work best if you use dictionaries.
You can make your dates and countries property a dictionary.
dates - Dates needs to be a dictionary because you can get data for different dates so the date will change
countries - The service u are using support other countries. If you change the countries to a dictionary, then the structure below should work for any country, not just for US.
Your code structure will then look something like this:
public class Root
{
public Dictionary<string, Date> dates {get;set;}
public Metadata metadata { get; set; }
public Total total { get; set; }
public string updated_at { get; set; }
}
public class Date
{
public Dictionary<string, Country> countries {get;set;}
public Info info {get;set;}
}
public class Country
{
....
//Country properties here
}
public class Info
{
....
//Info properties here
}
public class Metadata
{
....
//Metadata properties here
}
public class Total
{
....
//Total properties here
}
you should then be able to process the data as follow
foreach(var kvp in root.dates)
{
// the key will be the date eg. '2020-11-05'.
// This you can convert to a date using DateTime.Parse() if you need too.
Console.WriteLine(kvp.Key);
// The value will be the Date object
var dateObj = kvp.Value;
var info = dateObj.info;
foreach(var kvp2 in dateObj.countries)
{
Console.WriteLine(kvp2.Key); // this will be the country eg. 'US'
var countryDetails = kvp2.Value // this will be the Country object
}
}
Or just change your code too:
(note: you will need to know exactly what date was returned)
var paystoday_confirmed = response?.dates["2020-11-05"].countries["US"].today_confirmed;
if (paystoday_confirmed != null)
{
Debug.Log("Confirmed :" + paystoday_confirmed);
}
As already stated in the Comments your main issue here is that you hardcoded
public class Dates
{
[JsonProperty("2020-11-02")]
public _20201102 date { get; set; }
}
But as you can see in your second result the date simply is not 2020-11-02 but rather 2020-10-11!
Therefore in this case there is no object in the json representing the data object => It will be the default reference value null.
So how to solve this?
You could instead use a Dictionary .. however it depends a lot on how your JSON library works. I know that at least with JSON .Net the following should work
public class Root
{
public Dictionary<string, Date> dates { get; set; }
public Metadata metadata { get; set; }
public Total total { get; set; }
public string updated_at { get; set; }
}
public class Date
{
public Dictionary<string, Country> countries { get; set; }
public Info info { get; set; }
}
public class Country
{
public string date { get; set; }
public string id { get; set; }
public List<Link> links { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public List<Region> regions { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public double today_vs_yesterday_confirmed { get; set; }
public double today_vs_yesterday_deaths { get; set; }
public double today_vs_yesterday_open_cases { get; set; }
public double today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
}
This also sounds more logic since dates indicates that there might be more then one item. And also countries sounds like there might not only be US but also other countries, maybe even multiple entries.
You would then access that e.g. like
foreach(var date in response.dates)
{
foreach(var country in date.value)
{
var paystoday_confirmed = country.value.today_confirmed;
Debug.Log($"Confirmed {paystoday_confirmed} cases for the {date.key} in {country.key}");
}
}
As complete alternative in the case you only need one certain field of your request anyway you could also use SimpleJson (simply copy the provided scripts somewhere into your project) and access them like
var root = JSON.Parse(theJsonString);
var paystoday_confirmed = root["Dates"]["2020-11-05"]["countries"]["US"]["today_confirmed"].AsInt();
For both solutions you will have to get rid of that RestClient package and rather do the UnityWebRequest.Get yourself and use the returned string instead.
I know [FromBody] allows only one complex type as a parameter. I just wanted to know, is there any other way to do so? Any help or knowledge would be greatly appreciated! Thanks! :)
This is my controller
public HttpResponseMessage Post([FromBody] List<TranInOutDtl> tranInOutDtl, List<TranInOutDtlsub> tranDtlSub, List<TranInOutDtlsub> tranDtlSub)
This is my complex object below
public partial class TranInOutDtl
{
public int Tranno { get; set; }
public int Trannosub { get; set; }
public string ProdTypeDesc { get; set; }
public string BatchNo { get; set; }
public string Itemno { get; set; }
public string ItemDesc { get; set; }
public decimal ScanPendQty { get; set; }
public int TotalBoxqty { get; set; }
public decimal Quantity { get; set; }
public int BoxQty { get; set; }
public bool Isdone { get; set; }
public int PKId { get; set; }
public int PKSubId { get; set; }
public string PkBxDesc { get; set; }
public int BoxSz { get; set; }
}
public partial class TranInOutDtlsub
{
public int Tranno { get; set; }
public int Trannosub { get; set; }
public int Trannosub1 { get; set; }
public string RackShlvNo { get; set; }
public string ShlvNo { get; set; }
public int ShlvBoxQty { get; set; }
public decimal Quantity { get; set; }
public int BoxQty { get; set; }
public bool Isdonesub { get; set; }
public string RkShlvSelType { get; set; }
public string RkShCatUId { get; set; }
public string RackCatDesc { get; set; }
public string RkShCatColorCode { get; set; }
}
public partial class TranInOutRackScan
{
public int Tranno { get; set; }
public int Trannosub { get; set; }
public int Trannosub1 { get; set; }
public int Srno { get; set; }
public string BarcodeNo { get; set; }
public decimal Quantity { get; set; }
public int BoxQty { get; set; }
public string InOut { get; set; }
public int PackMaster_ID { get; set; }
public int Pack_type_ID { get; set; }
}
As it was mentioned by DavidG you could create any complex types that will suit your specific needs so for example
public class TranInOutContainer
{
public List<TranInOutDtl> TranInOutDtl Dtl {get; set;}
public List<TranInOutDtlsub> TranDtlSub DtlSub {get; set;}
....
}
will be valid solution for your problem
You could also use dynamic type ofc but it should be used only if no other solution exists
So I have a bunch of json files inside a folder and I want to merge them all into 1 big json file.
So I know you can do this, but I'm not sure how to to add that into a loop so it keeps adding onto 1.
var jObject1 = // Your first json object as JObject
var jObject2 = // Your second json object as JObject
jObject1.Merge(jObject2);
Here is some sample data
https://hatebin.com/iuqscvgmqk
I've made classes to model the object
But the issue I'm facing is that I don't know how to merge them all into 1 big file, I wanted to use a foreach, kinda like this
foreach (var file in Directory.GetFiles("Path"))
{
}
public class Requirements
{
public int ranged { get; set; }
}
public class Equipment
{
public int attack_stab { get; set; }
public int attack_slash { get; set; }
public int attack_crush { get; set; }
public int attack_magic { get; set; }
public int attack_ranged { get; set; }
public int defence_stab { get; set; }
public int defence_slash { get; set; }
public int defence_crush { get; set; }
public int defence_magic { get; set; }
public int defence_ranged { get; set; }
public int melee_strength { get; set; }
public int ranged_strength { get; set; }
public int magic_damage { get; set; }
public int prayer { get; set; }
public string slot { get; set; }
public Requirements requirements { get; set; }
}
public class Stance
{
public string combat_style { get; set; }
public object attack_type { get; set; }
public object attack_style { get; set; }
public string experience { get; set; }
public string boosts { get; set; }
}
public class Weapon
{
public int attack_speed { get; set; }
public string weapon_type { get; set; }
public List<Stance> stances { get; set; }
}
public class Item
{
public int id { get; set; }
public string name { get; set; }
public bool incomplete { get; set; }
public bool members { get; set; }
public bool tradeable { get; set; }
public bool tradeable_on_ge { get; set; }
public bool stackable { get; set; }
public bool noted { get; set; }
public bool noteable { get; set; }
public object linked_id_item { get; set; }
public int linked_id_noted { get; set; }
public int linked_id_placeholder { get; set; }
public bool placeholder { get; set; }
public bool equipable { get; set; }
public bool equipable_by_player { get; set; }
public bool equipable_weapon { get; set; }
public int cost { get; set; }
public int lowalch { get; set; }
public int highalch { get; set; }
public double weight { get; set; }
public int buy_limit { get; set; }
public bool quest_item { get; set; }
public string release_date { get; set; }
public bool duplicate { get; set; }
public string examine { get; set; }
public string icon { get; set; }
public string wiki_name { get; set; }
public string wiki_url { get; set; }
public Equipment equipment { get; set; }
public Weapon weapon { get; set; }
}
If you're trying to combine them as json, you'd need an array. So you'd combine those objects like this:
var ja = new JArray();
ja.Add(jObject1);
ja.Add(jObject2);
You of course could then later convert to your .NET object later if that's what your end goal is.
I need to extract data from a JSON string from a specific url (this).
When I convert it into C# by using jsontocsharp.com it looks like this:
public class Publisher
{
public int id { get; set; }
public string name { get; set; }
}
public class Title
{
public int id { get; set; }
public string name { get; set; }
public int subscribers { get; set; }
}
public class Issue
{
public List<object> alternates { get; set; }
public string complete_title { get; set; }
public string cover_image { get; set; }
public string description { get; set; }
public string diamond_id { get; set; }
public int id { get; set; }
public bool is_parent { get; set; }
public double? issue_number { get; set; }
public string other { get; set; }
public double price { get; set; }
public Publisher publisher { get; set; }
public string release_date { get; set; }
public Title title { get; set; }
}
public class RootObject
{
public int count { get; set; }
public string date { get; set; }
public List<Issue> issues { get; set; }
public int next { get; set; }
public object prev { get; set; }
public int total { get; set; }
}
Now I need to use these as my classes so I can gather and use data on further layers of my project. But I don't know how should I put the url in my code. I think this is a very basic question but I couldn't quite get the answer I'm looking for in the other questions. Any help greatly appreciated thank you.
I`m new in programming winodws 8 app , i have a webservice when i try to connect it using httprequest (Using URL with variables), this service return this:
{"d":"{\"sessionid\":\"twzv50okccwvgggeesjje2wa\",\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":2,\"PriceChangedTimer\":25,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":false,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"VertexFX 10\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1444\",\"Username\":\"test\",\"LastTickTime\":\"\/Date(1396307573431)\/\",\"SelectedAccount\":78821860,\"Name\":0,\"ServicePath\":null,\"GWSessionID\":\"56630\",\"IP\":\"Web (212.35.90.211)\",\"SessionDateStart\":\"01/04/2014 02:12:53\",\"CompanyName\":\"Hybrid Solutions\",\"UserId\":6119,\"DemoClient\":\"0\",\"FName\":\"omqrstu\",\"SName\":\"\",\"TName\":\"\",\"LName\":\"\",\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"2\",\"AlertSms\":\"2\",\"Temp\":null,\"GMTOffset\":\"2\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"1\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Welcome to V 10\",\"DealerTreePriv\":1}"}
i have simple windows app with one button when i click the button i send the url with variables and i got the obj above , i want to use content of this object like UserID in if statement but with no vain i dont know how to use it in C# , can and body help me??
I use this code. I know it has many errors but I need someone guide me.
private void Button_Click(object sender, RoutedEventArgs e)
{
String uriString = "url";
var uri = new Uri(uriString);
var httpWebRequest = HttpWebRequest.Create(uri);
httpWebRequest.BeginGetResponse(new AsyncCallback(OnGettingResponse), httpWebRequest);
}
private void OnGettingResponse(IAsyncResult ar)
{
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );
MessageBox.Show(root.UserId);
}
This is kind of a nasty situation. What you're getting back is a JSON object with a single property (i.e. d) and that property contains a string of JSON. So you basically need to unwrap the inner JSON from it's envelope. The following classes/code should work (using JSON.NET to do the deserialization).
public class OuterRootObject
{
public string d { get; set; }
}
public class Globals
{
public bool MultiSessionsAllowed { get; set; }
public int CommCalcType { get; set; }
public int PriceChangedTimer { get; set; }
public int ValidLotsLocation { get; set; }
public bool CustumizeTradeMsg { get; set; }
public object FirstWhiteLabeledOffice { get; set; }
public int DealerTreePriv { get; set; }
public int ClientConnectTimer { get; set; }
public int ClientTimeoutTimer { get; set; }
public double DefaultLots { get; set; }
public string WebSecurityID { get; set; }
public int ServerGMT { get; set; }
}
public class VersionInfo
{
public int Rel { get; set; }
public int Ver { get; set; }
public int Patch { get; set; }
public int ForceUpdate { get; set; }
public int UpdateType { get; set; }
public Globals Globals { get; set; }
}
public class SystemLockInfo
{
public int MinutesRemaining { get; set; }
public int HoursRemaining { get; set; }
public int DaysRemaining { get; set; }
public int Maintanance { get; set; }
public int WillBeLocked { get; set; }
}
public class RootObject
{
public string sessionid { get; set; }
public VersionInfo VersionInfo { get; set; }
public SystemLockInfo SystemLockInfo { get; set; }
public string FirstWhiteLabel { get; set; }
public string WLID { get; set; }
public bool CheckWhiteLabel { get; set; }
public string Password { get; set; }
public string Username { get; set; }
public DateTime LastTickTime { get; set; }
public int SelectedAccount { get; set; }
public int Name { get; set; }
public object ServicePath { get; set; }
public string GWSessionID { get; set; }
public string IP { get; set; }
public string SessionDateStart { get; set; }
public string CompanyName { get; set; }
public int UserId { get; set; }
public string DemoClient { get; set; }
public string FName { get; set; }
public string SName { get; set; }
public string TName { get; set; }
public string LName { get; set; }
public object Sms { get; set; }
public string isReadOnly { get; set; }
public string SchSms { get; set; }
public string AlertSms { get; set; }
public object Temp { get; set; }
public string GMTOffset { get; set; }
public string SvrGMT { get; set; }
public object ClientType { get; set; }
public string EnableNews { get; set; }
public string PublicSlideNews { get; set; }
public string PrivateSlideNews { get; set; }
public int DealerTreePriv { get; set; }
}
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );