Deserialize JSON to a class (Newtonsoft, C#) - c#

I am trying to save JSON data into my Class. I've tried different ways but didn't succeed.
Here is my class:
class YoCurrency
{
public string Currency { get; set; }
public double high { get; set; }
public double low { get; set; }
public double avg { get; set; }
public double vol { get; set; }
[JsonProperty("vol_cur")]
public double vol_cur { get; set; }
public double last { get; set; }
public double buy { get; set; }
public double sell { get; set; }
public int updated { get; set; }
}
Here is JSON file.
Trying to deserialize with generic List:
List<YoCurrency> a = JsonConvert.DeserializeObject<List<YoCurrency>>(json);
gives an error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[YoBitParser.YobitCurrency]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'btc_usd', line 1, position 11.'
Deserializing this way:
var a = JsonConvert.DeserializeObject<YobitCurrency>(json);
Doesn't give any result, because all class fields get 0 value
Also I tried to use two classes like this:
class YoCurrency
{
public double high { get; set; }
public double low { get; set; }
public double avg { get; set; }
public double vol { get; set; }
[JsonProperty("vol_cur")]
public double vol_cur { get; set; }
public double last { get; set; }
public double buy { get; set; }
public double sell { get; set; }
public int updated { get; set; }
}
class YoPair
{
YoCurrency Currency { get; set; }
string Name { get; set; }
}
But it didn't give any positive result. I tried to generate c# classes using http://json2csharp.com, but it generates a class for every currency:
public class BtcUsd
{
public double high { get; set; }
public double low { get; set; }
public double avg { get; set; }
public double vol { get; set; }
public double vol_cur { get; set; }
public double last { get; set; }
public double buy { get; set; }
public double sell { get; set; }
public int updated { get; set; }
}
public class EthUsd
{
...
}
public class RootObject
{
public BtcUsd btc_usd { get; set; }
public EthUsd eth_usd { get; set; }
...
}
But i suppose it's not good way in case of 50 or 500 pairs (or should I create a unique class for every currency?)
So please help me to deserialize this JSON or give me some information that could help me to solve this problem.

Why not just make one class?
class Program
{
static void Main(string[] args)
{
var array = "[{\"btc_usd\":[{\"high\":8550.0102,\"low\":7800,\"avg\":8175.0051,\"vol\":1615543.57397705,\"vol_cur\":197.54076079,\"last\":7850,\"buy\":7850.00000000,\"sell\":7879.00000000,\"updated\":1521383863}],\"eth_usd\":[{\"high\":622.93708559,\"low\":482,\"avg\":552.46854279,\"vol\":346598.40520112,\"vol_cur\":630.37075493,\"last\":488.27857735,\"buy\":489.77564548,\"sell\":492.11726255,\"updated\":1521383876}]}]";
List<RootObject> a = JsonConvert.DeserializeObject<List<RootObject>>(array);
}
}
public class RootCurrency
{
public double high { get; set; }
public int low { get; set; }
public double avg { get; set; }
public double vol { get; set; }
public double vol_cur { get; set; }
public double last { get; set; }
public double buy { get; set; }
public double sell { get; set; }
public int updated { get; set; }
}
public class RootObject
{
public List<RootCurrency> btc_usd { get; set; }
public List<RootCurrency> eth_usd { get; set; }
}

It look like your class structure is not proper, suggest you to generate class with the help of Visual Studio like as below and try your code by using generated class
based on your json strucutre you need class design like this
public class Rootobject
{
// do List<CurrencyDetail> if you are expecting multiple element
public CurrencyDetail btc_usd { get; set; }
public CurrencyDetail eth_usd { get; set; }
public CurrencyDetail doge_usd { get; set; }
public CurrencyDetail pac_usd { get; set; }
public CurrencyDetail rdd_usd { get; set; }
}
public class CurrencyDetail
{
public float high { get; set; }
public int low { get; set; }
public float avg { get; set; }
public float vol { get; set; }
public float vol_cur { get; set; }
public float last { get; set; }
public float buy { get; set; }
public float sell { get; set; }
public int updated { get; set; }
}
my suggesting is if possible modify you json , which will contain currency type in currency detail than you class strucutre will be like
public class Rootobject
{
public List<CurrencyDetail> currencies { get; set; }
}
public class CurrencyDetail
{
//btc_usd or eth_usd or doge_usd or pac_usd
public string type { get; set; }
public float high { get; set; }
public int low { get; set; }
public float avg { get; set; }
public float vol { get; set; }
public float vol_cur { get; set; }
public float last { get; set; }
public float buy { get; set; }
public float sell { get; set; }
public int updated { get; set; }
}

Related

Swagger Newtonsoft.Json.JsonSerializationException: Required property 'parcel_Triclops_Data' expects a non-null value

I have the following classes:
public class TriclopsParcelDataViewModel
{
public long ParcelId { get; set; }
public string ParcelSkuType { get; set; }
public string ParcelDescription { get; set; }
public Parcel_Triclops_Data Parcel_Triclops_Data { get; set; }
}
public class Parcel_Triclops_Data
{
[Key]
public long ParcelId { get; set; }
public DateTime Timestamp { get; set; }
public double WidthCm { get; set; }
public double HeightCm { get; set; }
public double DepthCm { get; set; }
public double WeightKg { get; set; }
public string TriclopsImage { get; set; }
}
TriclopsParcelDataViewModel is given as a result in one of my swagger/api endpoints.
I have then generated a client from the swagger definition.
When i call the function i get the following error:
Newtonsoft.Json.JsonSerializationException: Required property 'parcel_Triclops_Data' expects a non-null value. Path '[0]', line 1, position 99.
When i look at the json returned it looks like this:
[{"parcelId":13121,"parcelSkuType":"luggage-xl","parcelDescription":"","parcel_Triclops_Data":null},{"parcelId":13122,"parcelSkuType":"luggage-xl","parcelDescription":"","parcel_Triclops_Data":null},{"parcelId":13123,"parcelSkuType":"luggage-xl","parcelDescription":"","parcel_Triclops_Data":null},{"parcelId":13124,"parcelSkuType":"luggage-xl","parcelDescription":"","parcel_Triclops_Data":null}]
I get the feeling i need to override the json serialization settings in the generated client but unsure if i am correct.
Can anyone shed any light please?
I think your code should look like this:
public class TriclopsParcelDataViewModel
{
public Parcel_Triclops_Data ParcelId { get; set; } //changed from long to Parcel_Triclops_Data
public string ParcelSkuType { get; set; }
public string ParcelDescription { get; set; }
public Parcel_Triclops_Data Parcel_Triclops_Data { get; set; }
}
public class Parcel_Triclops_Data
{
[Key]
public long ParcelId { get; set; }
public DateTime Timestamp { get; set; }
public double WidthCm { get; set; }
public double HeightCm { get; set; }
public double DepthCm { get; set; }
public double WeightKg { get; set; }
public string TriclopsImage { get; set; }
}

i can't deserializing into JSON in C#. Is it something wrong with my classes?

I'm having trouble when tryin to Deserialize a string into JSON.
I'm making a call to a API. The anwer i get is stored i a variable(body)
Root Api = JsonConvert.DeserializeObject<Root>(body);
//var json = JsonConvert.DeserializeObject<Root>(body);
public partial class All
{
public int matchsPlayed { get; set; }
public int win { get; set; }
public int draw { get; set; }
public int lose { get; set; }
public int goalsFor { get; set; }
public int goalsAgainst { get; set; }
}
public partial class Home
{
public int matchsPlayed { get; set; }
public int win { get; set; }
public int draw { get; set; }
public int lose { get; set; }
public int goalsFor { get; set; }
public int goalsAgainst { get; set; }
}
public partial class Away
{
public int matchsPlayed { get; set; }
public int win { get; set; }
public int draw { get; set; }
public int lose { get; set; }
public int goalsFor { get; set; }
public int goalsAgainst { get; set; }
}
public partial class Standings // Offers
{
public int rank { get; set; }
public int team_id { get; set; }
public string teamName { get; set; }
public string logo { get; set; }
public string group { get; set; }
public string forme { get; set; }
public string status { get; set; }
public string description { get; set; }
public All all { get; set; }
public Home home { get; set; }
public Away away { get; set; }
public int goalsDiff { get; set; }
public int points { get; set; }
public string lastUpdate { get; set; }
}
public partial class Api // ProductListing
{
public int results { get; set; }
// public Standings[] Standings { get; set; }
public List<Standings> standings { get; set; }
}
public partial class Root // RootObject
{
public Api api { get; set; }
}
I get this error message: "
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'Standings' because the type requires a JSON object (e.g.
{"name":"value"}) to deserialize correctly. To fix this error either
change the JSON to a JSON object (e.g. {"name":"value"}) or change the
deserialized type to an array or a type that implements a collection
interface (e.g. ICollection, IList) like List that can be
deserialized from a JSON array. JsonArrayAttribute can also be added
to the type to force it to deserialize from a JSON array.
"
This is the whole json text i'm tryin to deserialize:
> {"api":{"results":1,"standings":[[{"rank":1,"team_id":45,"teamName":"Everton","logo":"https:\/\/media.api-sports.io\/football\/teams\/45.png","group":"Premier League","forme":"DWWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":5,"win":4,"draw":1,"lose":0,"goalsFor":14,"goalsAgainst":7},"home":{"matchsPlayed":3,"win":2,"draw":1,"lose":0,"goalsFor":11,"goalsAgainst":6},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":3,"goalsAgainst":1},"goalsDiff":7,"points":13,"lastUpdate":"2020-10-19"},{"rank":2,"team_id":66,"teamName":"Aston Villa","logo":"https:\/\/media.api-sports.io\/football\/teams\/66.png","group":"Premier League","forme":"WWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":4,"win":4,"draw":0,"lose":0,"goalsFor":12,"goalsAgainst":2},"home":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":8,"goalsAgainst":2},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":4,"goalsAgainst":0},"goalsDiff":10,"points":12,"lastUpdate":"2020-10-19"},{"rank":3,"team_id":40,"teamName":"Liverpool","logo":"https:\/\/media.api-sports.io\/football\/teams\/40.png","group":"Premier League","forme":"DLWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":5,"win":3,"draw":1,"lose":1,"goalsFor":13,"goalsAgainst":13},"home":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":7,"goalsAgainst":4},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":6,"goalsAgainst":9},"goalsDiff":0,"points":10,"lastUpdate":"2020-10-19"},{"rank":4,"team_id":46,"teamName":"Leicester","logo":"https:\/\/media.api-sports.io\/football\/teams\/46.png","group":"Premier League","forme":"LLWWW","status":"same","description":"Promotion - Champions League (Group Stage)","all":{"matchsPlayed":5,"win":3,"draw":0,"lose":2,"goalsFor":12,"goalsAgainst":8},"home":{"matchsPlayed":3,"win":1,"draw":0,"lose":2,"goalsFor":4,"goalsAgainst":6},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":8,"goalsAgainst":2},"goalsDiff":4,"points":9,"lastUpdate":"2020-10-19"},{"rank":5,"team_id":42,"teamName":"Arsenal","logo":"https:\/\/media.api-sports.io\/football\/teams\/42.png","group":"Premier League","forme":"LWLWW","status":"same","description":"Promotion - Europa League (Group Stage)","all":{"matchsPlayed":5,"win":3,"draw":0,"lose":2,"goalsFor":8,"goalsAgainst":6},"home":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":4,"goalsAgainst":2},"away":{"matchsPlayed":3,"win":1,"draw":0,"lose":2,"goalsFor":4,"goalsAgainst":4},"goalsDiff":2,"points":9,"lastUpdate":"2020-10-19"},{"rank":6,"team_id":39,"teamName":"Wolves","logo":"https:\/\/media.api-sports.io\/football\/teams\/39.png","group":"Premier League","forme":"WWLLW","status":"same","description":null,"all":{"matchsPlayed":5,"win":3,"draw":0,"lose":2,"goalsFor":5,"goalsAgainst":7},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":2,"goalsAgainst":3},"away":{"matchsPlayed":3,"win":2,"draw":0,"lose":1,"goalsFor":3,"goalsAgainst":4},"goalsDiff":-2,"points":9,"lastUpdate":"2020-10-19"},{"rank":7,"team_id":47,"teamName":"Tottenham","logo":"https:\/\/media.api-sports.io\/football\/teams\/47.png","group":"Premier League","forme":"DWDWL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":2,"lose":1,"goalsFor":15,"goalsAgainst":8},"home":{"matchsPlayed":3,"win":0,"draw":2,"lose":1,"goalsFor":4,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":11,"goalsAgainst":3},"goalsDiff":7,"points":8,"lastUpdate":"2020-10-19"},{"rank":8,"team_id":49,"teamName":"Chelsea","logo":"https:\/\/media.api-sports.io\/football\/teams\/49.png","group":"Premier League","forme":"DWDLW","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":2,"lose":1,"goalsFor":13,"goalsAgainst":9},"home":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":7,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":1,"draw":1,"lose":0,"goalsFor":6,"goalsAgainst":4},"goalsDiff":4,"points":8,"lastUpdate":"2020-10-19"},{"rank":9,"team_id":48,"teamName":"West Ham","logo":"https:\/\/media.api-sports.io\/football\/teams\/48.png","group":"Premier League","forme":"DWWLL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":11,"goalsAgainst":7},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":4,"goalsAgainst":2},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":7,"goalsAgainst":5},"goalsDiff":4,"points":7,"lastUpdate":"2020-10-19"},{"rank":10,"team_id":63,"teamName":"Leeds","logo":"https:\/\/media.api-sports.io\/football\/teams\/63.png","group":"Premier League","forme":"LDWWL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":9,"goalsAgainst":9},"home":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":5,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":4,"goalsAgainst":4},"goalsDiff":0,"points":7,"lastUpdate":"2020-10-19"},{"rank":11,"team_id":50,"teamName":"Manchester City","logo":"https:\/\/media.api-sports.io\/football\/teams\/50.png","group":"Premier League","forme":"WDLW","status":"same","description":null,"all":{"matchsPlayed":4,"win":2,"draw":1,"lose":1,"goalsFor":7,"goalsAgainst":7},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":3,"goalsAgainst":5},"away":{"matchsPlayed":2,"win":1,"draw":1,"lose":0,"goalsFor":4,"goalsAgainst":2},"goalsDiff":0,"points":7,"lastUpdate":"2020-10-19"},{"rank":12,"team_id":41,"teamName":"Southampton","logo":"https:\/\/media.api-sports.io\/football\/teams\/41.png","group":"Premier League","forme":"DWWLL","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":8,"goalsAgainst":9},"home":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":4,"goalsAgainst":5},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":4,"goalsAgainst":4},"goalsDiff":-1,"points":7,"lastUpdate":"2020-10-19"},{"rank":13,"team_id":34,"teamName":"Newcastle","logo":"https:\/\/media.api-sports.io\/football\/teams\/34.png","group":"Premier League","forme":"LWDLW","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":7,"goalsAgainst":9},"home":{"matchsPlayed":3,"win":1,"draw":0,"lose":2,"goalsFor":4,"goalsAgainst":8},"away":{"matchsPlayed":2,"win":1,"draw":1,"lose":0,"goalsFor":3,"goalsAgainst":1},"goalsDiff":-2,"points":7,"lastUpdate":"2020-10-19"},{"rank":14,"team_id":52,"teamName":"Crystal Palace","logo":"https:\/\/media.api-sports.io\/football\/teams\/52.png","group":"Premier League","forme":"DLLWW","status":"same","description":null,"all":{"matchsPlayed":5,"win":2,"draw":1,"lose":2,"goalsFor":6,"goalsAgainst":8},"home":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":3,"goalsAgainst":3},"away":{"matchsPlayed":2,"win":1,"draw":0,"lose":1,"goalsFor":3,"goalsAgainst":5},"goalsDiff":-2,"points":7,"lastUpdate":"2020-10-19"},{"rank":15,"team_id":33,"teamName":"Manchester United","logo":"https:\/\/media.api-sports.io\/football\/teams\/33.png","group":"Premier League","forme":"WLWL","status":"same","description":null,"all":{"matchsPlayed":4,"win":2,"draw":0,"lose":2,"goalsFor":9,"goalsAgainst":12},"home":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":2,"goalsAgainst":9},"away":{"matchsPlayed":2,"win":2,"draw":0,"lose":0,"goalsFor":7,"goalsAgainst":3},"goalsDiff":-3,"points":6,"lastUpdate":"2020-10-19"},{"rank":16,"team_id":51,"teamName":"Brighton","logo":"https:\/\/media.api-sports.io\/football\/teams\/51.png","group":"Premier League","forme":"DLLWL","status":"same","description":null,"all":{"matchsPlayed":5,"win":1,"draw":1,"lose":3,"goalsFor":9,"goalsAgainst":11},"home":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":3,"goalsAgainst":6},"away":{"matchsPlayed":3,"win":1,"draw":1,"lose":1,"goalsFor":6,"goalsAgainst":5},"goalsDiff":-2,"points":4,"lastUpdate":"2020-10-19"},{"rank":17,"team_id":60,"teamName":"West Brom","logo":"https:\/\/media.api-sports.io\/football\/teams\/60.png","group":"Premier League","forme":"DLDLL","status":"same","description":null,"all":{"matchsPlayed":5,"win":0,"draw":2,"lose":3,"goalsFor":5,"goalsAgainst":13},"home":{"matchsPlayed":3,"win":0,"draw":2,"lose":1,"goalsFor":3,"goalsAgainst":6},"away":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":2,"goalsAgainst":7},"goalsDiff":-8,"points":2,"lastUpdate":"2020-10-19"},{"rank":18,"team_id":44,"teamName":"Burnley","logo":"https:\/\/media.api-sports.io\/football\/teams\/44.png","group":"Premier League","forme":"DLLL","status":"same","description":"Relegation - Championship","all":{"matchsPlayed":4,"win":0,"draw":1,"lose":3,"goalsFor":3,"goalsAgainst":8},"home":{"matchsPlayed":1,"win":0,"draw":0,"lose":1,"goalsFor":0,"goalsAgainst":1},"away":{"matchsPlayed":3,"win":0,"draw":1,"lose":2,"goalsFor":3,"goalsAgainst":7},"goalsDiff":-5,"points":1,"lastUpdate":"2020-10-19"},{"rank":19,"team_id":62,"teamName":"Sheffield Utd","logo":"https:\/\/media.api-sports.io\/football\/teams\/62.png","group":"Premier League","forme":"DLLLL","status":"same","description":"Relegation - Championship","all":{"matchsPlayed":5,"win":0,"draw":1,"lose":4,"goalsFor":2,"goalsAgainst":7},"home":{"matchsPlayed":3,"win":0,"draw":1,"lose":2,"goalsFor":1,"goalsAgainst":4},"away":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":1,"goalsAgainst":3},"goalsDiff":-5,"points":1,"lastUpdate":"2020-10-19"},{"rank":20,"team_id":36,"teamName":"Fulham","logo":"https:\/\/media.api-sports.io\/football\/teams\/36.png","group":"Premier League","forme":"DLLLL","status":"same","description":"Relegation - Championship","all":{"matchsPlayed":5,"win":0,"draw":1,"lose":4,"goalsFor":4,"goalsAgainst":12},"home":{"matchsPlayed":2,"win":0,"draw":0,"lose":2,"goalsFor":0,"goalsAgainst":6},"away":{"matchsPlayed":3,"win":0,"draw":1,"lose":2,"goalsFor":4,"goalsAgainst":6},"goalsDiff":-8,"points":1,"lastUpdate":"2020-10-19"}]]}}
If you change the definition of Api so standings is a list of lists it should work as the JSON has an array of arrays.
public partial class Api // ProductListing
{
public int results { get; set; }
public List<List<Standings>> standings { get; set; }
}

NewtonSoft JSON Deserialization: System.StackOverflowException

The JSON deserialization is failing with the exception System.StackOverflowException.
I'm trying the deserialize the following entity. Need help, why this is causing the issue.
var workingJSONString = "{\"FBTOrLeaseYear\":{\"DateFrom\":\"2019-03-02T00:00:00\",\"DateTo\":\"2020-03-01T00:00:00\"},\"Registration\":\"155SQN\",\"NovatedLeaseFortnightBenefitGroups\":[],\"NovatedLeaseAnnualBenefitGroups\":[]}";
var exceptionJSONString = "{\"FBTOrLeaseYear\":{\"DateFrom\":\"2019-03-02T00:00:00\",\"DateTo\":\"2020-03-01T00:00:00\"},\"Registration\":\"155SQN\",\"NovatedLeaseFortnightBenefitGroups\":[{\"BenefitGroupID\":1,\"BenefitGroupName\":\"Fuel\",\"TotalAnnualBudgetAmount\":4992.0000,\"TotalFortnightBudgetAmount\":192.0000,\"TotalSpentToDate\":3327.43,\"TotalFortnightSpent\":141.59276595744680851063829788,\"TotalProjAnnualAmount\":3681.4119148936170212765957447,\"TotalVariationAmount\":1310.5880851063829787234042553,\"AverageSpentPercentage\":14.645499465811966666666666667,\"NovatedLeaseBudgetSpentDataForBenefits\":[]}],\"NovatedLeaseAnnualBenefitGroups\":[]}";
Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear novatedLeaseBenefitsBudgetSpentFBTYearResponse = new Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear();
novatedLeaseBenefitsBudgetSpentFBTYearResponse = JsonConvert.DeserializeObject<Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear>(exceptionJSONString); // Exception is thrown here
Entities:
On deserialization of the "Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear" entity,
I'm getting an exception "System.StackOverflowException". Can one please help me why the deserizarion is failing for this JSON.
public class NovatedLeaseBenefitsBudgetSpentFBTYear
{
public FBTOrLeaseYear FBTOrLeaseYear { get; set; }
public string Registration { get; set; }
public List<NovatedLeaseBenefitGroup> NovatedLeaseFortnightBenefitGroups { get; set; }
public List<NovatedLeaseBenefitGroup> NovatedLeaseAnnualBenefitGroups { get; set; }
}
public class NovatedLeaseBenefitGroup
{
public int BenefitGroupID { get; set; }
public string BenefitGroupName { get; set; }
public double TotalAnnualBudgetAmount { get; set; }
public double TotalFortnightBudgetAmount { get; set; }
public double TotalSpentToDate { get; set; }
public double TotalFortnightSpent { get; set; }
public double TotalProjAnnualAmount { get; set; }
public double TotalVariationAmount { get; set; }
public double AverageSpentPercentage { get; set; }
public List<NovatedLeaseBudgetSpentDataForBenefit> NovatedLeaseBudgetSpentDataForBenefits { get; set; }
}
public class NovatedLeaseBudgetSpentDataForBenefit
{
public int BenefitId { get; set; }
public string BenefitName { get; set; }
public double AnnualBudgetAmount { get; set; }
public double FortnightBudgetAmount { get; set; }
public double SpentToDate { get; set; }
public double FortnightSpent { get; set; }
public double ProjAnnualAmount { get; set; }
public double VariationAmount { get; set; }
public double SpentPercentage { get; set; }
}
public class FBTOrLeaseYear
{
public string DateFrom { get; set; }
public string DateTo { get; set; }
}

Extracting JSON data Xamarin

I am working a Xamarin.Forms App that uses the Azure Face API. With this API you retrieve a JSON response (See Below).
I want to extract the gender of the person in the image but am having trouble with it as I am very new to this.
I extract the full JSON response into a string but I would like to be able to extract data such as the 'Gender' or the 'Age' of the person in the image.
[{"faceId":"9448dfe4-afb6-4557-94fe-010fc439ff36","faceRectangle":{"top":635,"left":639,"width":789,"height":789},"faceAttributes":{"smile":0.187,"headPose":{"pitch":0.0,"roll":-1.6,"yaw":-7.9},"gender":"male","age":34.6,"facialHair":{"moustache":0.5,"beard":0.6,"sideburns":0.6},"glasses":"NoGlasses","emotion":{"anger":0.0,"contempt":0.69,"disgust":0.0,"fear":0.0,"happiness":0.187,"neutral":0.12,"sadness":0.002,"surprise":0.0},"blur":{"blurLevel":"low","value":0.15},"exposure":{"exposureLevel":"overExposure","value":0.85},"noise":{"noiseLevel":"medium","value":0.42},"makeup":{"eyeMakeup":false,"lipMakeup":false},"accessories":[],"occlusion":{"foreheadOccluded":false,"eyeOccluded":false,"mouthOccluded":false},"hair":{"bald":0.02,"invisible":false,"hairColor":[{"color":"brown","confidence":1.0},{"color":"black","confidence":0.95},{"color":"other","confidence":0.22},{"color":"blond","confidence":0.11},{"color":"gray","confidence":0.05},{"color":"red","confidence":0.04}]}}}]
This is how I set the JSON data to a string.
string contentString = await response.Content.ReadAsStringAsync();
You usually want to create a class that represents your response e. g. Person. Then you could use the Newtonsoft.Json nuget package to deserialize the object.:
var person = JsonConvert.DeserializeObject<Person>(contentString);
Now you can access the values like:
person.Gender
Using Newtonsoft.Json:
var results = JsonConvert.DeserializeObject<AzureFace>(contentString);
Debug.WriteLine(results.faceAttributes.age);
C# Model Used (via http://jsonutils.com)
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class HeadPose
{
public double pitch { get; set; }
public double roll { get; set; }
public double yaw { get; set; }
}
public class FacialHair
{
public double moustache { get; set; }
public double beard { get; set; }
public double sideburns { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class Blur
{
public string blurLevel { get; set; }
public double value { get; set; }
}
public class Exposure
{
public string exposureLevel { get; set; }
public double value { get; set; }
}
public class Noise
{
public string noiseLevel { get; set; }
public double value { get; set; }
}
public class Makeup
{
public bool eyeMakeup { get; set; }
public bool lipMakeup { get; set; }
}
public class Occlusion
{
public bool foreheadOccluded { get; set; }
public bool eyeOccluded { get; set; }
public bool mouthOccluded { get; set; }
}
public class HairColor
{
public string color { get; set; }
public double confidence { get; set; }
}
public class Hair
{
public double bald { get; set; }
public bool invisible { get; set; }
public IList<HairColor> hairColor { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public HeadPose headPose { get; set; }
public string gender { get; set; }
public double age { get; set; }
public FacialHair facialHair { get; set; }
public string glasses { get; set; }
public Emotion emotion { get; set; }
public Blur blur { get; set; }
public Exposure exposure { get; set; }
public Noise noise { get; set; }
public Makeup makeup { get; set; }
public IList<object> accessories { get; set; }
public Occlusion occlusion { get; set; }
public Hair hair { get; set; }
}
public class AzureFace
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}

JSON deserialize dictionaries with varying keys

I'd like to deserialize some JSON strings like this:
{"time":1506174868,"pairs":{
"AAA":{"books":8,"min":0.1,"max":1.0,"fee":0.01},
"AAX":{"books":8,"min":0.1,"max":1.0,"fee":0.01},
"AQA":{"books":8,"min":0.1,"max":1.0,"fee":0.01}
}}
where AAA, AAX, ... there are hundreds of variations
I paste this Json as class in VS2017 and get the following:
public class Rootobject
{
public int time { get; set; }
public Pairs pairs { get; set; }
}
public class Pairs
{
public AAA AAA { get; set; }
public AAX AAX { get; set; }
public AQA AQA { get; set; }
}
public class AAA
{
public int books { get; set; }
public float min { get; set; }
public float max { get; set; }
public float fee { get; set; }
}
public class AAX
{
public int books { get; set; }
public float min { get; set; }
public float max { get; set; }
public float fee { get; set; }
}
public class AQA
{
public int books { get; set; }
public float min { get; set; }
public float max { get; set; }
public float fee { get; set; }
}
I'd try to avoid hundreds of class declarations since all classes are same except
their name.
I tried to serialize this as array or list but I get exception since this is not an array.
I use Newtonsoft JSON lib.
Thank you
Sure, you can parse the json string to object as follows:
public class Rootobject
{
public int time { get; set; }
public Dictionary<string, ChildObject> pairs { get; set; }
}
public class ChildObject
{
public int books { get; set; }
public float min { get; set; }
public float max { get; set; }
public float fee { get; set; }
}
class Program
{
static string json = #"
{""time"":1506174868,""pairs"":{
""AAA"":{""books"":8,""min"":0.1,""max"":1.0,""fee"":0.01},
""AAX"":{""books"":8,""min"":0.1,""max"":1.0,""fee"":0.01},
""AQA"":{""books"":8,""min"":0.1,""max"":1.0,""fee"":0.01}
}
}";
static void Main(string[] args)
{
Rootobject root = JsonConvert.DeserializeObject<Rootobject>(json);
foreach(var child in root.pairs)
{
Console.WriteLine(string.Format("Key: {0}, books:{1},min:{2},max:{3},fee:{4}",
child.Key, child.Value.books, child.Value.max, child.Value.min, child.Value.fee));
}
}
thisextendsthat's answer is fine for your specific case. However, there are fully dynamic options for deserialization:
1) Parse into an JToken
var root = JObject.Parse(jsonString);
var time = root["time"];
2) Parse into a dynamic
dynamic d = JObject.Parse(jsonString);
var time = d.time;

Categories