I'm trying to deserialize a JSON from here. And I can't use i.e. properties from class Global.
namespace CoVID2
{
public class CovidStats
{
public string ID { get; set; }
public string Message { get; set; }
public class Global {
public int NewConfirmed { get; set; }
public int TotalConfirmed { get; set; }
public int NewDeaths { get; set; }
public int TotalDeaths { get; set; }
public int NewRecovered { get; set; }
public int TotalRecovered { get; set; }
public string Date { get; set; }
}
}
private void button1_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
string s = client.DownloadString(url);
CovidStats stat = JsonConvert.DeserializeObject<CovidStats>(s);
MessageBox.Show(stat.Global.TotalConfirmed.ToString()); // This is the place, where i get an error
}
}
Error CS0572 'Global': cannot reference a type through an expression; try 'CovidStats.Global' instead CoVID2 C:\Users\Yan\source\repos\CoVID2\CoVID2\Form1.cs 64 Active
Error CS0120 An object reference is required for the non-static field, method, or property 'CovidStats.Global.TotalConfirmed' CoVID2 C:\Users\Yan\source\repos\CoVID2\CoVID2\Form1.cs 64 Active
You can use https://json2csharp.com/ to easily convert valid JSON string into C# classes.
Based on the JSON from https://api.covid19api.com/summary I got the following result:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Global
{
public int NewConfirmed { get; set; }
public int TotalConfirmed { get; set; }
public int NewDeaths { get; set; }
public int TotalDeaths { get; set; }
public int NewRecovered { get; set; }
public int TotalRecovered { get; set; }
public DateTime Date { get; set; }
}
public class Premium
{
}
public class Country
{
public string ID { get; set; }
public string Country { get; set; }
public string CountryCode { get; set; }
public string Slug { get; set; }
public int NewConfirmed { get; set; }
public int TotalConfirmed { get; set; }
public int NewDeaths { get; set; }
public int TotalDeaths { get; set; }
public int NewRecovered { get; set; }
public int TotalRecovered { get; set; }
public DateTime Date { get; set; }
public Premium Premium { get; set; }
}
public class Root
{
public string ID { get; set; }
public string Message { get; set; }
public Global Global { get; set; }
public List<Country> Countries { get; set; }
public DateTime Date { get; set; }
}
Related
I have these classes
public class ResponseEntryInfoAndTollDue
{
public int Code { get; set; }
public string Message { get; set; }
public TagEntryInfo TagEntryInfo { get; set; }
public TollMatrix TollMatrix { get; set; }
public List<TagInfoParam> TagInfoParams { get; set; }
public ResponseEntryInfoAndTollDue()
{
TagEntryInfo = new TagEntryInfo();
TollMatrix = new TollMatrix();
TagInfoParams = new List<TagInfoParam>();
}
}
public class TagEntryInfo
{
public long TrxnID { get; set; }
public string TagRFIDNumber { get; set; }
public string EntryTrxnDTime { get; set; }
public int EntryPlaza { get; set; }
public short EntryLane { get; set; }
public string EntryDirection { get; set; }
public string EntryLaneType { get; set; }
public string PostingDateTime { get; set; }
public string Action { get; set; }
}
public class TollMatrix
{
public decimal TollDue { get; set; }
public decimal TollVat { get; set; }
public decimal TollNoVat { get; set; }
public bool IsDefaulted { get; set; }
}
public class TagInfoParam
{
public DateTime? AsOfDate { get; set; }
public Decimal? AvailableBalance { get; set; }
public string TagNumber { get; set; }
public string PLateNumber { get; set; }
public Int16 HonorPlate { get; set; }
public Int16 TagStatusID { get; set; }
public string TID { get; set; }
public string EPC { get; set; }
public string AccountTypeID { get; set; }
public Int16 AccountStatusID { get; set; }
public Int16 TagClassID { get; set; }
public Int16 Status { get; set; }
}
From a webservice I get this json string:
{"Result":{"Code":0,"Message":"With entry info computed toll due","TagEntryInfo":{"TrxnID":6666750,"TagRFIDNumber":"1234567890","EntryTrxnDTime":"2021-01-16 16:40:16.560","EntryPlaza":123,"EntryLane":1,"EntryDirection":"B","EntryLaneType":"A","PostingDateTime":"2021-01-16T16:43:16.05","Action":"A"},"TollMatrix":{"TollDue":164.0000,"TollVat":17.5700,"TollNoVat":146.4300,"IsDefaulted":false},"TagInfoParams":[{"AsOfDate":"2021-01-16T17:12:04.213","AvailableBalance":537.0000,"TagNumber":"1234567890","PLateNumber":"Q123","HonorPlate":1,"TagStatusID":1,"TID":"Elfkajs98","EPC":"889080990709","AccountTypeID":"REV","AccountStatusID":1,"TagClassID":1,"Status":1}]},"Id":351,"Exception":null,"Status":5,"IsCanceled":false,"IsCompleted":true,"CreationOptions":0,"AsyncState":null,"IsFaulted":false}
This is how I convert it:
var response = JsonConvert.DeserializeObject(ret);
I know that it doesn't get converted because this is what I get:
This is the result:
Why is this not being converted into an object?
As Fabio also mentioned that your json contains the attribute Result which is not part of your object so you can use below logic to deserialize
var jObj = JObject.Parse(json);
var responseEntryInfoAndTollDue = JsonConvert.DeserializeObject<ResponseEntryInfoAndTollDue>(jObj["Result"].ToString());
The above code first parse the Json to JObject and uses Result property to deserialize to ResponseEntryInfoAndTollDue object.
Check this fiddle - https://dotnetfiddle.net/7Pc3sJ
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 am working with processing/consuming some data from: https://ashesescalation-api-tachyon.stardock.net/v1/products/2641/leaderboards/ladder/de5bfc9a-9092-4014-b52e-89151de42646?offset=0&count=2 (which can be opened easily in Firefox to view.)
I am able to access the data in C# by doing this:
data being the json data...
dynamic players = JArray.Parse(data);
var p = players[0];
Console.Write(p.personaName);
However I am having trouble accessing the part in the JSON data: "dataInteger" for example the "totalUnitsKilled."
p.dataInteger[0].totalUnitsKilled
That "p.dataInteger[0].totalUnitsKilled" doesn't work.
How can I access that data in C#?
Thank you very much for your help.
Warren
See image in visual studio 1
See image in visual studio 2
Kinldy take a look at my comment in your question, base on that link you need to use JsonProperty to mapped the key that has special characters and manually named it based on your needs.
Anyways, you can do the following to achieved what you need.
Copy your link to http://json2csharp.com/
Copy the generated Quicktypes and paste it to your code.
Use JsonProperty to indicate attributes on your properties for the names and manually rename properties that contains invalid_name
And DeserializeObject the object.
Here is the code:
Declare the classes from the generated quicktypes.
public class DataInteger
{
[JsonProperty(PropertyName = "totalUnitsKilled ")]
public int totalUnitsKilled { get; set; }
public int totalTitansKilled { get; set; }
public int totalTimePlayed { get; set; }
[JsonProperty(PropertyName = "substrate-TotalGamesPlayed")]
public int SubstrateTotalGamesPlayed { get; set; }
[JsonProperty(PropertyName = "phC-TotalGamesPlayed")]
public int PHCTotalGamesPlayed { get; set; }
public int lastReplayVersion { get; set; }
public int replayUploadedCount { get; set; }
}
public class RootObject
{
public string personaLadderId { get; set; }
public int rank { get; set; }
public string personaId { get; set; }
public string personaName { get; set; }
public string avatarUrl { get; set; }
public string avatarUrlSmall { get; set; }
public string avatarUrlMedium { get; set; }
public string avatarUrlLarge { get; set; }
public string ladderType { get; set; }
public string ladderId { get; set; }
public string seasonId { get; set; }
public int bracketId { get; set; }
public string bracketName { get; set; }
public int rankingScore { get; set; }
public int secondaryScore { get; set; }
public int ruleTypeId { get; set; }
public int wins { get; set; }
public int losses { get; set; }
public int ties { get; set; }
public int tieStreak { get; set; }
public int winStreak { get; set; }
public int lossStreak { get; set; }
public int longestTieStreak { get; set; }
public int longestWinStreak { get; set; }
public int longestLossStreak { get; set; }
public int bracketMaxScore { get; set; }
public int bracketScore { get; set; }
public DateTime updateDate { get; set; }
public int totalMatchesPlayed { get; set; }
public DataInteger dataInteger { get; set; }
}
Call the API (Magic begins here)
var httpClient = new HttpClient();
var link = $#"https://ashesescalation-api-tachyon.stardock.net/v1/products/2641/leaderboards/ladder/de5bfc9a-9092-4014-b52e-89151de42646?offset=0&count=2";
var response = await httpClient.GetAsync(link);
var contents = await response.Content.ReadAsStringAsync();
//deserialized json result object...
dynamic json = JsonConvert.DeserializeObject(contents);
foreach (var item in json)
{
//deserialized again the item
var data = JsonConvert.DeserializeObject<RootObject>(Convert.ToString(item));
//you can now access all the properties including dataInteger.
Console.WriteLine(Convert.ToString(data.dataInteger.totalUnitsKilled));
Console.WriteLine(Convert.ToString(data.dataInteger.totalTitansKilled));
}
Update:
If you don't want to use strongly typed class you can do parsing using JArray
JArray jsonVal = JArray.Parse(contents) as JArray;
dynamic items = jsonVal;
foreach (dynamic item in items)
{
var x = item.dataInteger;
//you can access the fields inside dataInteger.
Console.WriteLine(x["totalUnitsKilled "]);
Console.WriteLine(x["phC-TotalGamesPlayed"]);
Console.WriteLine(x["substrate-TotalGamesPlayed"]);
}
Hope this will help you.
As suggested by other users, there is a space in property name "totalUnitsKilled ", if you change it to "totalUnitsKilled". Below code will work fine:-
Console.WriteLine(p.dataInteger.totalUnitsKilled);
Your JSON string is wrong.
[{"personaLadderId":"371eaf1c-4cfe-4873-af41-56e0cb9fcf91","rank":1,"personaId":"55834d01-13f3-445e-861f-0bc4769d87cc","personaName":"Amelie","avatarUrl":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg","avatarUrlSmall":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg","avatarUrlMedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_medium.jpg","avatarUrlLarge":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_full.jpg","ladderType":"Ranked","ladderId":"de5bfc9a-9092-4014-b52e-89151de42646","seasonId":"fd7dd807-4ac2-40ec-8476-a4b2937f70af","bracketId":0,"bracketName":"Legendary","rankingScore":38,"secondaryScore":2054,"ruleTypeId":1,"wins":374,"losses":32,"ties":0,"tieStreak":0,"winStreak":8,"lossStreak":0,"longestTieStreak":0,"longestWinStreak":61,"longestLossStreak":3,"bracketMaxScore":0,"bracketScore":0,"updateDate":"2018-03-03T14:13:09.647Z","totalMatchesPlayed":406,"dataInteger":{"totalUnitsKilled ":92615,"totalTitansKilled":14,"totalTimePlayed":294676,"substrate-TotalGamesPlayed":127,"phC-TotalGamesPlayed":6,"lastReplayVersion":265301040,"replayUploadedCount":160}},{"personaLadderId":"f0dd3482-f057-44d6-a626-9c9389ad2583","rank":2,"personaId":"b53815ab-d753-4415-9ea6-03a4519c3222","personaName":"Rebellions","avatarUrl":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b.jpg","avatarUrlSmall":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b.jpg","avatarUrlMedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b_medium.jpg","avatarUrlLarge":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b_full.jpg","ladderType":"Ranked","ladderId":"de5bfc9a-9092-4014-b52e-89151de42646","seasonId":"fd7dd807-4ac2-40ec-8476-a4b2937f70af","bracketId":0,"bracketName":"Legendary","rankingScore":38,"secondaryScore":2049,"ruleTypeId":1,"wins":767,"losses":188,"ties":0,"tieStreak":0,"winStreak":3,"lossStreak":0,"longestTieStreak":0,"longestWinStreak":52,"longestLossStreak":6,"bracketMaxScore":0,"bracketScore":0,"updateDate":"2017-10-29T18:03:33.92Z","totalMatchesPlayed":955,"dataInteger":{"totalUnitsKilled ":293274,"totalTitansKilled":88,"totalTimePlayed":924881,"phC-TotalGamesPlayed":4,"substrate-TotalGamesPlayed":350,"lastReplayVersion":250285270,"replayUploadedCount":703}}]
There is a space in your json key name ("totalUnitsKilled ") which is ultimately converted to a variable name.
Correct your JSON key name will fix this issue. There are other keys with error as well.
You can check at http://json2csharp.com/. Wherever it is "invalid_name", key name is wrong.
public class DataInteger
{
public int __invalid_name__totalUnitsKilled { get; set; }
public int totalTitansKilled { get; set; }
public int totalTimePlayed { get; set; }
public int __invalid_name__substrate-TotalGamesPlayed { get; set; }
public int __invalid_name__phC-TotalGamesPlayed { get; set; }
public int lastReplayVersion { get; set; }
public int replayUploadedCount { get; set; }
}
public class RootObject
{
public string personaLadderId { get; set; }
public int rank { get; set; }
public string personaId { get; set; }
public string personaName { get; set; }
public string avatarUrl { get; set; }
public string avatarUrlSmall { get; set; }
public string avatarUrlMedium { get; set; }
public string avatarUrlLarge { get; set; }
public string ladderType { get; set; }
public string ladderId { get; set; }
public string seasonId { get; set; }
public int bracketId { get; set; }
public string bracketName { get; set; }
public int rankingScore { get; set; }
public int secondaryScore { get; set; }
public int ruleTypeId { get; set; }
public int wins { get; set; }
public int losses { get; set; }
public int ties { get; set; }
public int tieStreak { get; set; }
public int winStreak { get; set; }
public int lossStreak { get; set; }
public int longestTieStreak { get; set; }
public int longestWinStreak { get; set; }
public int longestLossStreak { get; set; }
public int bracketMaxScore { get; set; }
public int bracketScore { get; set; }
public DateTime updateDate { get; set; }
public int totalMatchesPlayed { get; set; }
public DataInteger dataInteger { get; set; }
}
You can use JSON.Net attributes to define C# variables related to JSON key names. Check this for more details.
Your new class should look like:
public class DataInteger
{
[JsonProperty(PropertyName = "totalUnitsKilled ")]
public int totalUnitsKilled { get; set; }
public int totalTitansKilled { get; set; }
public int totalTimePlayed { get; set; }
[JsonProperty(PropertyName = "substrate-TotalGamesPlayed")]
public int substrateTotalGamesPlayed { get; set; }
[JsonProperty(PropertyName = "phC-TotalGamesPlayed")]
public int phCTotalGamesPlayed { get; set; }
public int lastReplayVersion { get; set; }
public int replayUploadedCount { get; set; }
}
I have a class with nested subclasses:
public class listDevicesModel
{
public int totalCount { get; set; }
public Messages messages { get; set; }
public Devices devices { get; set; }
public class Entry
{
public string key { get; set; }
public object value { get; set; }
}
public class Detail
{
public List<Entry> entry { get; set; }
}
public class Devices
{
public List<Device> device { get; set; }
}
public class Device
{
public string #id { get; set; }
public string uuid { get; set; }
public string principal { get; set; }
public int blockReason { get; set; }
public int clientId { get; set; }
public string comment { get; set; }
public int compliance { get; set; }
public int countryCode { get; set; }
public int countryId { get; set; }
public string countryName { get; set; }
public string createdAt { get; set; }
public string currentPhoneNumber { get; set; }
public List<Detail> details { get; set; }
public int deviceCount { get; set; }
public string easLastSyncAttempt { get; set; }
public string easUuid { get; set; }
public string emailAddress { get; set; }
public string emailDomain { get; set; }
public bool employeeOwned { get; set; }
public string homeOperator { get; set; }
public int languageCountryId { get; set; }
public int languageId { get; set; }
public string lastConnectedAt { get; set; }
public string manufacturer { get; set; }
public bool mdmManaged { get; set; }
public int mdmProfileUrlId { get; set; }
public string model { get; set; }
public string name { get; set; }
public bool notifyUser { get; set; }
public string #operator { get; set; }
public int operatorId { get; set; }
public string platform { get; set; }
public string platformType { get; set; }
public int quarantinedStatus { get; set; }
public int regCount { get; set; }
public string regType { get; set; }
public string registeredAt { get; set; }
public string status { get; set; }
public int statusCode { get; set; }
public string userDisplayName { get; set; }
public string userFirstName { get; set; }
public string userLastName { get; set; }
public int userSource { get; set; }
public string userUUID { get; set; }
public int wipeReason { get; set; }
}
}
In my MVC razor view i try to access the data:
#model PostenNorge.Models.JsonObjectModels.listDevicesModel
<b>#Model.messages.message</b>
<br />
<br />
<ul>
#foreach(Device d in Model.devices.device)
{
<li>#d.name - #d.uuid - #d.currentPhoneNumber</li>
}
</ul>
On Device in the foreach i get "The type or namespace name "Device" could not be found".
How can i access the nested class types in my view?
You need to specify the nested name:
#foreach(listDevicesModel.Device d in Model.devices.device)
Or use implicit typing:
#foreach(var d in Model.devices.device)
Personally I'd avoid using nested classes here anyway, unless you really have to. Even if you do really have to, I'd rename the top-level class to follow normal naming conventions, i.e. make it start with a capital letter.
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 );