I have a nested json string, instead of using arrays the next level is another json structure. This creates a mess of deserializing using traditional methods.
Most other answers dealing with parsing json have clearly defined structures, and in most cases can be solved using online tools such as http://json2csharp.com/. But because this JSON doesn't use arrays properly I'm having trouble coming up with a solution to deserialize it.
For example:
{
"time":1516824466,
"global":{
"workers":1,
"hashrate":0
},
"algos":{
"scrypt-n":{
"workers":1,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
}
},
"pools":{
"garlicoin":{
"name":"garlicoin",
"symbol":"GRLC",
"algorithm":"scrypt-n",
"poolStats":{
"validShares":"22855",
"validBlocks":"3",
"invalidShares":"59",
"invalidRate":"0.0026",
"totalPaid":"296.42722209999999999"
},
"blocks":{
"pending":0,
"confirmed":2,
"orphaned":1
},
"workers":{
"Gf3ZXqhWKkm8qLhSHvyrawiCiooYeU9eQu":{
"shares":365.07991498000007,
"invalidshares":0,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
},
"Gz2Llan6hTkm8qLhSHh34awiCiooYe17heT":{
"shares":365.07991498000007,
"invalidshares":0,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
}
},
"hashrate":79752.92436043094,
"workerCount":1,
"hashrateString":"79.75 KH"
}
}
}
I'm having trouble deserializing these two parts specifically:
"algos":{
"scrypt-n":{
"workers":1,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
}
},
"workers":{
"Gf3ZXqhWKkm8qLhSHvyrawiCiooYeU9eQu":{
"shares":365.07991498000007,
"invalidshares":0,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
},
"Gz2Llan6hTkm8qLhSHh34awiCiooYe17heT":{
"shares":365.07991498000007,
"invalidshares":0,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
}
},
The Code I've Tried
namespace pooldecode
{
public static class Serialize
{
public static string ToJson(this jsonDecode.Root self)
{
return JsonConvert.SerializeObject(self, Converter.Settings);
}
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
public class jsonDecode
{
public static Root FromJson(string json) => JsonConvert.DeserializeObject<Root>(json/*, Converter.Settings*/);
public partial class Root
{
[J("time")] public long Time { get; set; }
[J("global")] public Global Global { get; set; }
[J("algos")] public List<Algos> Algos { get; set; }
[J("pools")] public List<Pools> Pools { get; set; }
}
public partial class Algos
{
[J("workers")] public int Workers { get; set; }
[J("hashrate")] public double Hashrate { get; set; }
[J("hashrateString")] public string HashrateString { get; set; }
}
public partial class Global
{
[J("workers")] public int Workers { get; set; }
[J("hashrate")] public long Hashrate { get; set; }
}
public partial class Pools
{
[J("crypto")] public List<Crypto> Crypto { get; set; }
}
public partial class Crypto
{
[J("name")] public string Name { get; set; }
[J("symbol")] public string Symbol { get; set; }
[J("algorithm")] public string Algorithm { get; set; }
[J("poolStats")] public PoolStats PoolStats { get; set; }
[J("blocks")] public Blocks Blocks { get; set; }
[J("workers")] public Workers Workers { get; set; }
[J("hashrate")] public double Hashrate { get; set; }
[J("workerCount")] public long WorkerCount { get; set; }
[J("hashrateString")] public string HashrateString { get; set; }
}
public partial class Blocks
{
[J("pending")] public long Pending { get; set; }
[J("confirmed")] public long Confirmed { get; set; }
[J("orphaned")] public long Orphaned { get; set; }
}
public partial class PoolStats
{
[J("validShares")] public string ValidShares { get; set; }
[J("validBlocks")] public string ValidBlocks { get; set; }
[J("invalidShares")] public string InvalidShares { get; set; }
[J("invalidRate")] public string InvalidRate { get; set; }
[J("totalPaid")] public string TotalPaid { get; set; }
}
public partial class Workers
{
[J("worker")] public List<Workers> Worker { get; set; }
[J("shares")] public double Shares { get; set; }
[J("invalidshares")] public long Invalidshares { get; set; }
[J("hashrate")] public double Hashrate { get; set; }
[J("hashrateString")] public string HashrateString { get; set; }
}
public partial class Worker
{
[J("shares")] public double Shares { get; set; }
[J("invalidshares")] public long Invalidshares { get; set; }
[J("hashrate")] public double Hashrate { get; set; }
[J("hashrateString")] public string HashrateString { get; set; }
}
}
}
Algos, Pools and Workers have named properties as childrens, you can't deserialize them as List<T> since they are Dictionary<string, T>,
Use these classes to deserialize:
public partial class Root
{
[JsonPropertyAttribute("time")] public long Time { get; set; }
[JsonPropertyAttribute("global")] public Global Global { get; set; }
[JsonPropertyAttribute("algos")] public Dictionary<string, Algo> Algos { get; set; }
[JsonPropertyAttribute("pools")] public Dictionary<string, Pool> Pools { get; set; }
}
public partial class Global
{
[JsonPropertyAttribute("workers")] public int Workers { get; set; }
[JsonPropertyAttribute("hashrate")] public long Hashrate { get; set; }
}
public partial class Algo
{
[JsonPropertyAttribute("workers")] public int Workers { get; set; }
[JsonPropertyAttribute("hashrate")] public double Hashrate { get; set; }
[JsonPropertyAttribute("hashrateString")] public string HashrateString { get; set; }
}
public partial class Pool
{
[JsonPropertyAttribute("name")] public string Name { get; set; }
[JsonPropertyAttribute("symbol")] public string Symbol { get; set; }
[JsonPropertyAttribute("algorithm")] public string Algorithm { get; set; }
[JsonPropertyAttribute("poolStats")] public PoolStats PoolStats { get; set; }
[JsonPropertyAttribute("blocks")] public Blocks Blocks { get; set; }
[JsonPropertyAttribute("workers")] public Dictionary<string, Worker> Workers { get; set; }
[JsonPropertyAttribute("hashrate")] public double Hashrate { get; set; }
[JsonPropertyAttribute("workerCount")] public long WorkerCount { get; set; }
[JsonPropertyAttribute("hashrateString")] public string HashrateString { get; set; }
}
public partial class Blocks
{
[JsonPropertyAttribute("pending")] public long Pending { get; set; }
[JsonPropertyAttribute("confirmed")] public long Confirmed { get; set; }
[JsonPropertyAttribute("orphaned")] public long Orphaned { get; set; }
}
public partial class PoolStats
{
[JsonPropertyAttribute("validShares")] public string ValidShares { get; set; }
[JsonPropertyAttribute("validBlocks")] public string ValidBlocks { get; set; }
[JsonPropertyAttribute("invalidShares")] public string InvalidShares { get; set; }
[JsonPropertyAttribute("invalidRate")] public string InvalidRate { get; set; }
[JsonPropertyAttribute("totalPaid")] public string TotalPaid { get; set; }
}
public partial class Worker
{
[JsonPropertyAttribute("shares")] public double Shares { get; set; }
[JsonPropertyAttribute("invalidshares")] public long Invalidshares { get; set; }
[JsonPropertyAttribute("hashrate")] public double Hashrate { get; set; }
[JsonPropertyAttribute("hashrateString")] public string HashrateString { get; set; }
}
Related
I'm not sure what is causing this to happen. When debugging, I can step through each line, but when it hits the DeserializeObject line, the program doesn't do anything. I can no longer step over or do anything else with the program. No error messages are being thrown either.
[Command("stats")]
public async Task LookupMonsterStats(CommandContext ctx, string name)
{
string monstersUri = "https://www.dnd5eapi.co/api/monsters/";
var formatted = name.Replace(" ", "-");
string apiResponse = string.Empty;
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(monstersUri + formatted))
{
apiResponse = await response.Content.ReadAsStringAsync();
var monster = JsonConvert.DeserializeObject<Monster>(apiResponse);
}
}
await ctx.Channel.SendMessageAsync(apiResponse).ConfigureAwait(false);
}
Edit: Here is what my Monster class looks like
public class Monster
{
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("name")]
public string Name{ get; set; }
[JsonProperty("size")]
public string Size { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("subtype")]
public string Subtype { get; set; }
[JsonProperty("alignment")]
public string Alignment { get; set; }
[JsonProperty("armor_class")]
public int? ArmorClass { get; set; }
[JsonProperty("hit_points")]
public int? HitPoints { get; set; }
[JsonProperty("forms")]
public List<string> Forms { get; set; }
[JsonProperty("speed")]
public Object Speed { get; set; }
[JsonProperty("strength")]
public int? Strength { get; set; }
[JsonProperty("dexterity")]
public int? Dexterity { get; set; }
[JsonProperty("constitution")]
public int? Constitution { get; set; }
[JsonProperty("intelligence")]
public int? Intelligence { get; set; }
[JsonProperty("wisdom")]
public int? Wisdom { get; set; }
[JsonProperty("charisma")]
public int? Charisma { get; set; }
[JsonProperty("proficiencies")]
public List<string> Proficiencies { get; set; }
[JsonProperty("damage_vulnerabilities")]
public List<string> DamageVulnerabilities { get; set; }
[JsonProperty("damage_resistances")]
public List<string> DamageResistances { get; set; }
[JsonProperty("damage_immunities")]
public List<string> DamageImmunities { get; set; }
[JsonProperty("condition_immunities")]
public List<string> ConditionImmunities { get; set; }
[JsonProperty("senses")]
public Object Senses { get; set; }
[JsonProperty("languages")]
public string Languages { get; set; }
[JsonProperty("challenge_rating")]
public decimal? ChallengeRating { get; set; }
[JsonProperty("special_abilities")]
public List<string> SpecialAbilities { get; set; }
[JsonProperty("actions")]
public List<string> Actions { get; set; }
[JsonProperty("legendary_actions")]
public List<string> LegendaryActions { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
As mentioned in a comment your class definition doesn't seem to match the JSON response, assuming you're using Visual Studio it's probably worth opening Debug / Windows / Exception Settings and make sure "Common Language Runtime Exceptions" is checked. Sometimes I've found stepping over in multi-threaded apps can produce unusual results after an exception.
When I pasted your code into LINQPad I got errors on several members you've defined as List<string> when the underlying type is more complex. What I normally do to avoid those errors is copy the raw json from a browser window to the clipboard and with a CS file open in Visual Studio do an Edit / Paste Special / Paste JSON as classes to automatically create the classes. After doing that I got the following that deserialized the data fine:
async Task Main()
{
await LookupMonsterStats("aboleth");
}
public async Task LookupMonsterStats(string name)
{
string monstersUri = "https://www.dnd5eapi.co/api/monsters/";
var formatted = name.Replace(" ", "-");
string apiResponse = string.Empty;
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(monstersUri + formatted))
{
apiResponse = await response.Content.ReadAsStringAsync();
var monster = JsonConvert.DeserializeObject<Monster>(apiResponse);
monster.Dump();
}
}
}
public class Monster
{
public string index { get; set; }
public string name { get; set; }
public string size { get; set; }
public string type { get; set; }
public object subtype { get; set; }
public string alignment { get; set; }
public int armor_class { get; set; }
public int hit_points { get; set; }
public string hit_dice { get; set; }
public Speed speed { get; set; }
public int strength { get; set; }
public int dexterity { get; set; }
public int constitution { get; set; }
public int intelligence { get; set; }
public int wisdom { get; set; }
public int charisma { get; set; }
public Proficiency[] proficiencies { get; set; }
public object[] damage_vulnerabilities { get; set; }
public object[] damage_resistances { get; set; }
public object[] damage_immunities { get; set; }
public object[] condition_immunities { get; set; }
public Senses senses { get; set; }
public string languages { get; set; }
public int challenge_rating { get; set; }
public int xp { get; set; }
public Special_Abilities[] special_abilities { get; set; }
public Action[] actions { get; set; }
public Legendary_Actions[] legendary_actions { get; set; }
public string url { get; set; }
}
public class Speed
{
public string walk { get; set; }
public string swim { get; set; }
}
public class Senses
{
public string darkvision { get; set; }
public int passive_perception { get; set; }
}
public class Proficiency
{
public Proficiency1 proficiency { get; set; }
public int value { get; set; }
}
public class Proficiency1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Special_Abilities
{
public string name { get; set; }
public string desc { get; set; }
public Dc dc { get; set; }
}
public class Dc
{
public Dc_Type dc_type { get; set; }
public int dc_value { get; set; }
public string success_type { get; set; }
}
public class Dc_Type
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Action
{
public string name { get; set; }
public string desc { get; set; }
public Options options { get; set; }
public Damage[] damage { get; set; }
public int attack_bonus { get; set; }
public Dc1 dc { get; set; }
public Usage usage { get; set; }
}
public class Options
{
public int choose { get; set; }
public From[][] from { get; set; }
}
public class From
{
public string name { get; set; }
public int count { get; set; }
public string type { get; set; }
}
public class Dc1
{
public Dc_Type1 dc_type { get; set; }
public int dc_value { get; set; }
public string success_type { get; set; }
}
public class Dc_Type1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Usage
{
public string type { get; set; }
public int times { get; set; }
}
public class Damage
{
public Damage_Type damage_type { get; set; }
public string damage_dice { get; set; }
}
public class Damage_Type
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Legendary_Actions
{
public string name { get; set; }
public string desc { get; set; }
public int attack_bonus { get; set; }
public Damage1[] damage { get; set; }
}
public class Damage1
{
public Damage_Type1 damage_type { get; set; }
public string damage_dice { get; set; }
}
public class Damage_Type1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
I have a JSON with multidimensional array. I have no idea how to deserialize it on my c# model. I did a very simple way of deserialization which is not working. I need to know how to deserialize my JSON on more structural way.
This is my json data
{
"Access_point_result": [
{
"msg": {
"ap_eth_mac": {
"addr": "D8C7C8C0C7BE"
},
"ap_name": "1344-1-AL5",
"ap_group": "1344-hq",
"ap_model": "135",
"depl_mode": "DEPLOYMENT_MODE_CAMPUS",
"ap_ip_address": {
"af": "ADDR_FAMILY_INET",
"addr": "10.6.66.67",
"reboots": 1,
"rebootstraps": 2,
"managed_by": {
"af": "ADDR_FAMILY_INET",
"addr": "0.0.0.0"
},
"managed_by_key": "2e302bee0164cc154d1d266d8567ada44d49e77af82f4b5ccb",
"radios": {
"radio_bssid.addr": "D8.C7.C8.46.D8.10"
},
"is_master": true,
"ap_location": {
"ap_eth_mac": "D8C7C8C0C7BE",
"campus_id": "6F9DEC79839D458B9F148D16A46A353E",
"building_id": "83393A922FB249C1929B95393A2AAFDA",
"floor_id": "260BE76B0DD13E7AAF18EB3B47DD7F7B",
"longitude": -122.008,
"latitude": 37.4129,
"ap_x": 22.15,
"ap_y": 99.18
}
},
"ts": 1382046667
}
}
]
}
Below is my C# model
public class WifiDataAruba : BaseModel
{
public string APMACAddr { get; set; }
public string APName { get; set; }
public string APGroup { get; set; }
public string APModel { get; set; }
public string APDeplMode { get; set; }
public string APIPAddr { get; set; }
public int APReboots { get; set; }
public int APRebootStraps { get; set; }
public string APManagedBy { get; set; }
public string APManagedByKey { get; set; }
public string APRadios { get; set; }
public bool APMaster { get; set; }
public string APLocation { get; set; }
public string APMACAddr2 { get; set; }
public string APCampusID { get; set; }
public string APLocationID { get; set; }
public string APBuildingID { get; set; }
public string APFloorID { get; set; }
public double APLongtitude { get; set; }
public double APLatitude { get; set; }
public double X { get; set; }
public double Y { get; set; }
public DateTime ImportTimestamp { get; set; }
}
How can i make the break the deserialization much structural way?
you have to change your model to the following
public class ApEthMac
{
public string addr { get; set; }
}
public class ManagedBy
{
public string af { get; set; }
public string addr { get; set; }
}
public class Radios
{
public string __invalid_name__radio_bssid.addr { get; set; }
}
public class ApLocation
{
public string ap_eth_mac { get; set; }
public string campus_id { get; set; }
public string building_id { get; set; }
public string floor_id { get; set; }
public double longitude { get; set; }
public double latitude { get; set; }
public double ap_x { get; set; }
public double ap_y { get; set; }
}
public class ApIpAddress
{
public string af { get; set; }
public string addr { get; set; }
public int reboots { get; set; }
public int rebootstraps { get; set; }
public ManagedBy managed_by { get; set; }
public string managed_by_key { get; set; }
public Radios radios { get; set; }
public bool is_master { get; set; }
public ApLocation ap_location { get; set; }
}
public class Msg
{
public ApEthMac ap_eth_mac { get; set; }
public string ap_name { get; set; }
public string ap_group { get; set; }
public string ap_model { get; set; }
public string depl_mode { get; set; }
public ApIpAddress ap_ip_address { get; set; }
public int ts { get; set; }
}
public class AccessPointResult
{
public Msg msg { get; set; }
}
public class RootObject
{
public List<AccessPointResult> Access_point_result { get; set; }
}
and your webapi method should look like the following
public void Post(RootObject rootObject)
Note
that you have to add camelcaseconvention in your webapi config if you want to change your c# model to PascalCase
Here how your method should look like in your WebaApiConfig
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
EnableCrossSiteRequests(config);
// Web API routes
config.MapHttpAttributeRoutes();
GlobalConfiguration.Configuration.Formatters.JsonFormatter
.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Model
public class ApEthMac
{
public string addr { get; set; }
}
public class ManagedBy
{
public string af { get; set; }
public string addr { get; set; }
}
public class Radios
{
public string __invalid_name__radio_bssid.addr { get; set; }
}
public class ApLocation
{
public string ap_eth_mac { get; set; }
public string campus_id { get; set; }
public string building_id { get; set; }
public string floor_id { get; set; }
public double longitude { get; set; }
public double latitude { get; set; }
public double ap_x { get; set; }
public double ap_y { get; set; }
}
public class ApIpAddress
{
public string af { get; set; }
public string addr { get; set; }
public int reboots { get; set; }
public int rebootstraps { get; set; }
public ManagedBy managed_by { get; set; }
public string managed_by_key { get; set; }
public Radios radios { get; set; }
public bool is_master { get; set; }
public ApLocation ap_location { get; set; }
}
public class Msg
{
public ApEthMac ap_eth_mac { get; set; }
public string ap_name { get; set; }
public string ap_group { get; set; }
public string ap_model { get; set; }
public string depl_mode { get; set; }
public ApIpAddress ap_ip_address { get; set; }
public int ts { get; set; }
}
public class AccessPointResult
{
public Msg msg { get; set; }
}
public class RootObject
{
public List<AccessPointResult> Access_point_result { get; set; }
}
then DeserializeObject
RootObject rootObject= new RootObject();
rootObject= JsonConvert.DeserializeObject<RootObject>(jsonAgents);
Found an odd issue when trying to deserialize a JSON string into a C# Object. It "seems" to perform the operation successfully (as in it does not throw any exception etc), however the outputted POCO contains does not contain any data from the JSON string, it only contains type default data (nulls,"", 0 etc). I have tried this process with other JSON and it works fine.
private string GetJson()
{
return #"{""backdrop_path"":"" / 1LrtAhWPSEetJLjblXvnaYtl7eA.jpg"",""created_by"":[{""id"":488,""name"":""Steven Spielberg"",""profile_path"":"" / pOK15UNaw75Bzj7BQO1ulehbPPm.jpg""},{""id"":31,""name"":""Tom Hanks"",""profile_path"":"" / a14CNByTYALAPSGlwlmfHILpEIW.jpg""}],""episode_run_time"":[60],""first_air_date"":""2001 - 09 - 09"",""genres"":[{""id"":28,""name"":""Action""},{""id"":12,""name"":""Adventure""},{""id"":18,""name"":""Drama""},{""id"":10752,""name"":""War""}],""homepage"":""http://www.hbo.com/band-of-brothers"",""id"":4613,""in_production"":false,""languages"":[""de"",""fr"",""lt"",""nl"",""en""],""last_air_date"":""2001-11-04"",""name"":""Band of Brothers"",""networks"":[{""id"":49,""name"":""HBO""}],""number_of_episodes"":10,""number_of_seasons"":1,""origin_country"":[""GB"",""US""],""original_language"":""en"",""original_name"":""Band of Brothers"",""overview"":""Drawn from interviews with survivors of Easy Company, as well as their journals and letters, Band of Brothers chronicles the experiences of these men from paratrooper training in Georgia through the end of the war. As an elite rifle company parachuting into Normandy early on D-Day morning, participants in the Battle of the Bulge, and witness to the horrors of war, the men of Easy knew extraordinary bravery and extraordinary fear - and became the stuff of legend. Based on Stephen E. Ambrose's acclaimed book of the same name."",""popularity"":3.435181,""poster_path"":""/bUrt6oeXd04ImEwQjO9oLjRguaA.jpg"",""production_companies"":[{""name"":""DreamWorks SKG"",""id"":27},{""name"":""HBO Films"",""id"":7429},{""name"":""DreamWorks Television"",""id"":15258}],""seasons"":[{""air_date"":null,""episode_count"":4,""id"":14071,""poster_path"":""/bMN9iiSAdnmAjflREfCCH0TTNyQ.jpg"",""season_number"":0},{""air_date"":""2001-09-09"",""episode_count"":10,""id"":14070,""poster_path"":""/15SN18OVbYt12Wzttclh51Sz9m1.jpg"",""season_number"":1}],""status"":""Ended"",""type"":""Scripted"",""vote_average"":8.5,""vote_count"":47}";
}
[TestMethod]
public void DeserializeTmdbShowData_ValidShowData_ReturnDeserializedObject()
{
//Arrange
string jsonStream = GetJson();
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
//Act
var tmdbShowDetails = jsonSerializer.Deserialize<List<TmdbShowDetailsDto>>(jsonStream);
//Assert
Assert.IsNotNull(tmdbShowDetails);
Assert.IsNotNull(tmdbShowDetails.First().backdrop_path);
}
public class TmdbShowDetailsDto
{
public string backdrop_path { get; set; }
public Created_By[] created_by { get; set; }
public int[] episode_run_time { get; set; }
public string first_air_date { get; set; }
public Genre[] genres { get; set; }
public string homepage { get; set; }
public int id { get; set; }
public bool in_production { get; set; }
public string[] languages { get; set; }
public string last_air_date { get; set; }
public string name { get; set; }
public Network[] networks { get; set; }
public int number_of_episodes { get; set; }
public int number_of_seasons { get; set; }
public string[] origin_country { get; set; }
public string original_language { get; set; }
public string original_name { get; set; }
public string overview { get; set; }
public float popularity { get; set; }
public string poster_path { get; set; }
public Production_Companies[] production_companies { get; set; }
public Season[] seasons { get; set; }
public string status { get; set; }
public string type { get; set; }
public float vote_average { get; set; }
public int vote_count { get; set; }
}
public class Created_By
{
public int id { get; set; }
public string name { get; set; }
public string profile_path { get; set; }
}
public class Genre
{
public int id { get; set; }
public string name { get; set; }
}
public class Network
{
public int id { get; set; }
public string name { get; set; }
}
public class Production_Companies
{
public string name { get; set; }
public int id { get; set; }
}
public class Season
{
public string air_date { get; set; }
public int episode_count { get; set; }
public int id { get; set; }
public string poster_path { get; set; }
public int season_number { get; set; }
}
Any ideas - Im sure I have missed something glaringly obvious but I cannot see it. Using .NET 4.5
Help appreciated.
Cheers
I used http://json2csharp.com/, and the code is like this, so you should look at it.
public class Poster
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Images
{
public Poster poster { get; set; }
public Fanart fanart { get; set; }
}
public class Ids
{
public int trakt { get; set; }
public string slug { get; set; }
public int tvdb { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Show
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public string status { get; set; }
public Images images { get; set; }
public Ids ids { get; set; }
}
public class Poster2
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart2
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Images2
{
public Poster2 poster { get; set; }
public Fanart2 fanart { get; set; }
}
public class Ids2
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
}
public class Movie
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public Images2 images { get; set; }
public Ids2 ids { get; set; }
}
public class Headshot
{
public object full { get; set; }
public object medium { get; set; }
public object thumb { get; set; }
}
public class Images3
{
public Headshot headshot { get; set; }
}
public class Ids3
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Person
{
public string name { get; set; }
public Images3 images { get; set; }
public Ids3 ids { get; set; }
}
public class RootObject
{
public string type { get; set; }
public object score { get; set; }
public Show show { get; set; }
public Movie movie { get; set; }
public Person person { get; set; }
}
You can use Paste-Special Feature in your VS-IDE Paster JSON as Classes
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string type { get; set; }
public object score { get; set; }
public Show show { get; set; }
public Movie movie { get; set; }
public Person person { get; set; }
}
public class Show
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public string status { get; set; }
public Images images { get; set; }
public Ids ids { get; set; }
}
public class Images
{
public Poster poster { get; set; }
public Fanart fanart { get; set; }
}
public class Poster
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Ids
{
public int trakt { get; set; }
public string slug { get; set; }
public int tvdb { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Movie
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public Images1 images { get; set; }
public Ids1 ids { get; set; }
}
public class Images1
{
public Poster1 poster { get; set; }
public Fanart1 fanart { get; set; }
}
public class Poster1
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart1
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Ids1
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
}
public class Person
{
public string name { get; set; }
public Images2 images { get; set; }
public Ids2 ids { get; set; }
}
public class Images2
{
public Headshot headshot { get; set; }
}
public class Headshot
{
public object full { get; set; }
public object medium { get; set; }
public object thumb { get; set; }
}
public class Ids2
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
Look like you JSON string is not in correct format that you are trying to deserialize. For example i have not find show property in the C# class but it present in JSON.
So this issue I couldn't figure out in the night or early in the morning - it took me till this afternoon until I realised that I was had the wrong JSON!!, so no wonder it wasn't working! I got mixed up with a few different apis that provided JSON. Thanks to those who had pointed out that the class looks wrong, made me double check my code and realise the simplicity of this issue. Kinda needed some rubber ducking to spot the problem. Cheers
I am working on an integration with the Expedia API. I am relatively new to ServiceStack but have managed pretty well so far, however, I've hit an issue with the deserialization of a JSON response from the API which seems to be failing despite having JsConfig.ThrowOnDeserializationError enabled.
JsConfig.Reset();
JsConfig.ThrowOnDeserializationError = true;
var availability = _client.Get<ExpediaHotelRoomAvailability>("avail?" + querystring);
In order to see the API response I am working with please use the following request:
GET http://dev.api.ean.com/ean-services/rs/hotel/v3/avail?minorRev=26&cid=55505&apiKey=cbrzfta369qwyrm9t5b8y8kf&customerUserAgent=Mozilla%2f5.0+(Windows+NT+6.3%3b+WOW64)+AppleWebKit%2f537.36+(KHTML%2c+like+Gecko)+Chrome%2f35.0.1916.114+Safari%2f537.36&customerIpAddress=%3a%3a1&hotelId=135857&arrivalDate=06%2f07%2f2014&departureDate=06%2f20%2f2014&includeDetails=true&includeRoomImages=true&room1=2 HTTP/1.1
User-Agent: Fiddler
Content-Type: text/json
Host: dev.api.ean.com
Here is a typical response:
{
"HotelRoomAvailabilityResponse":{
"#size":"1",
"customerSessionId":"0ABAAA7A-D42E-2914-64D2-01C0F09040D8",
"hotelId":135857,
"arrivalDate":"06\/07\/2014",
"departureDate":"06\/20\/2014",
"hotelName":"La Quinta Inn and Suites Raleigh Cary",
"hotelAddress":"191 Crescent Commons",
"hotelCity":"Cary",
"hotelStateProvince":"NC",
"hotelCountry":"US",
"numberOfRoomsRequested":1,
"checkInInstructions":"",
"tripAdvisorRating":4.5,
"tripAdvisorReviewCount":189,
"tripAdvisorRatingUrl":"http:\/\/www.tripadvisor.com\/img\/cdsi\/img2\/ratings\/traveler\/4.5-12345-4.gif",
"HotelRoomResponse":{
"rateCode":14587,
"roomTypeCode":14587,
"rateDescription":"Standard Room, 1 King Bed",
"roomTypeDescription":"Standard Room, 1 King Bed",
"supplierType":"E",
"propertyId":67977,
"BedTypes":{
"#size":"1",
"BedType":{
"#id":"14",
"description":"1 king"
}
},
"smokingPreferences":"S,NS",
"rateOccupancyPerRoom":3,
"quotedOccupancy":2,
"minGuestAge":0,
"RateInfos":{
"#size":"1",
"RateInfo":{
"#priceBreakdown":"true",
"#promo":"false",
"#rateChange":"true",
"RoomGroup":{
"Room":{
"numberOfAdults":2,
"numberOfChildren":0,
"rateKey":"0214364d-6819-4631-aa97-a162c43e0297"
}
},
"ChargeableRateInfo":{
"#averageBaseRate":"109.61539",
"#averageRate":"109.61539",
"#commissionableUsdTotal":"1425.0",
"#currencyCode":"USD",
"#maxNightlyRate":"165.0",
"#nightlyRateTotal":"1425.0",
"#surchargeTotal":"229.19",
"#total":"1654.19",
"NightlyRatesPerRoom":{
"#size":"13",
"NightlyRate":[
{
"#baseRate":"90.0",
"#rate":"90.0",
"#promo":"false"
},
{
"#baseRate":"90.0",
"#rate":"90.0",
"#promo":"false"
},
{
"#baseRate":"100.0",
"#rate":"100.0",
"#promo":"false"
},
{
"#baseRate":"115.0",
"#rate":"115.0",
"#promo":"false"
},
{
"#baseRate":"115.0",
"#rate":"115.0",
"#promo":"false"
},
{
"#baseRate":"115.0",
"#rate":"115.0",
"#promo":"false"
},
{
"#baseRate":"165.0",
"#rate":"165.0",
"#promo":"false"
},
{
"#baseRate":"165.0",
"#rate":"165.0",
"#promo":"false"
},
{
"#baseRate":"90.0",
"#rate":"90.0",
"#promo":"false"
},
{
"#baseRate":"95.0",
"#rate":"95.0",
"#promo":"false"
},
{
"#baseRate":"95.0",
"#rate":"95.0",
"#promo":"false"
},
{
"#baseRate":"95.0",
"#rate":"95.0",
"#promo":"false"
},
{
"#baseRate":"95.0",
"#rate":"95.0",
"#promo":"false"
}
]
},
"Surcharges":{
"#size":"1",
"Surcharge":{
"#type":"TaxAndServiceFee",
"#amount":"229.19"
}
}
},
"cancellationPolicy":"We understand that sometimes your travel plans change. We do not charge a change or cancel fee. However, this property (La Quinta Inn and Suites Raleigh Cary) imposes the following penalty to its customers that we are required to pass on: Cancellations or changes made after 6:00 PM ((GMT-05:00) Eastern Time (US & Canada)) on Jun 6, 2014 are subject to a 1 Night Room & Tax penalty. The property makes no refunds for no shows or early checkouts.",
"CancelPolicyInfoList":{
"CancelPolicyInfo":[
{
"versionId":208699803,
"cancelTime":"18:00:00",
"startWindowHours":0,
"nightCount":1,
"currencyCode":"USD",
"timeZoneDescription":"(GMT-05:00) Eastern Time (US & Canada)"
},
{
"versionId":208778550,
"cancelTime":"18:00:00",
"startWindowHours":24,
"nightCount":0,
"currencyCode":"USD",
"timeZoneDescription":"(GMT-05:00) Eastern Time (US & Canada)"
}
]
},
"nonRefundable":false,
"rateType":"MerchantStandard",
"currentAllotment":0,
"guaranteeRequired":false,
"depositRequired":true,
"taxRate":229.19
}
},
"ValueAdds":{
"#size":"3",
"ValueAdd":[
{
"#id":"2048",
"description":"Free Wireless Internet"
},
{
"#id":"2",
"description":"Continental Breakfast"
},
{
"#id":"128",
"description":"Free Parking"
}
]
},
"deepLink":"https:\/\/travel.ian.com\/templates\/55505\/hotels\/135857\/book?lang=en&standardCheckin=06\/07\/2014&standardCheckout=06\/20\/2014&selectedPrice=1654.190000&supplierType=E&rateCode=14587&roomTypeCode=14587&roomsCount=1&rooms[0].adultsCount=2&rateKey=0214364d-6819-4631-aa97-a162c43e0297",
"RoomImages":{
"#size":"1",
"RoomImage":{
"url":"http:\/\/media.expedia.com\/hotels\/1000000\/70000\/68000\/67977\/67977_103_s.jpg"
}
}
}
}
}
A large part of the response is de-serialized fine except for all of the rate information which I am really interested in. No exceptions are thrown during the deserialization so I have little to go on in terms of tracking down the exact problem. To be more specific let's take the ChargeableRateInfo - all values contained within are either null or zero.
Here is my class I am trying to deserialize the response to:
namespace MyCustomNamespace
{
using System.Collections.Generic;
public class BedType
{
public string description { get; set; }
public string id { get; set; }
}
public class BedTypes
{
public BedType BedType { get; set; }
public int size { get; set; }
}
public class Room
{
public int numberOfAdults { get; set; }
public int numberOfChildren { get; set; }
public string rateKey { get; set; }
}
public class RoomGroup
{
public Room Room { get; set; }
}
public class NightlyRate
{
public string baseRate { get; set; }
public string promo { get; set; }
public string rate { get; set; }
}
public class NightlyRatesPerRoom
{
public List<NightlyRate> NightlyRate { get; set; }
public int size { get; set; }
}
public class Surcharge
{
public decimal amount { get; set; }
public string type { get; set; }
}
public class Surcharges
{
public Surcharge Surcharge { get; set; }
public int size { get; set; }
}
public class ChargeableRateInfo
{
public NightlyRatesPerRoom NightlyRatesPerRoom { get; set; }
public Surcharges Surcharges { get; set; }
public decimal averageBaseRate { get; set; }
public decimal averageRate { get; set; }
public decimal commissionableUsdTotal { get; set; }
public string currencyCode { get; set; }
public decimal maxNightlyRate { get; set; }
public decimal nightlyRateTotal { get; set; }
public decimal surchargeTotal { get; set; }
public decimal total { get; set; }
}
public class CancelPolicyInfo
{
public string cancelTime { get; set; }
public string currencyCode { get; set; }
public int nightCount { get; set; }
public int percent { get; set; }
public int startWindowHours { get; set; }
public string timeZoneDescription { get; set; }
public int versionId { get; set; }
}
public class CancelPolicyInfoList
{
public List<CancelPolicyInfo> CancelPolicyInfo { get; set; }
}
public class RateInfo
{
public CancelPolicyInfoList CancelPolicyInfoList { get; set; }
public ChargeableRateInfo ChargeableRateInfo { get; set; }
public RoomGroup RoomGroup { get; set; }
public string cancellationPolicy { get; set; }
public int currentAllotment { get; set; }
public bool depositRequired { get; set; }
public bool guaranteeRequired { get; set; }
public bool nonRefundable { get; set; }
public string priceBreakdown { get; set; }
public string promo { get; set; }
public string promoType { get; set; }
public string rateChange { get; set; }
public string rateType { get; set; }
public decimal taxRate { get; set; }
}
public class RateInfos
{
public RateInfo RateInfo { get; set; }
public int size { get; set; }
}
public class ValueAdd
{
public string description { get; set; }
public string id { get; set; }
}
public class ValueAdds
{
public List<ValueAdd> ValueAdd { get; set; }
public int size { get; set; }
}
public class RoomImage
{
public string url { get; set; }
}
public class RoomImages
{
public RoomImage RoomImage { get; set; }
public int size { get; set; }
}
public class HotelRoomResponse
{
public BedTypes BedTypes { get; set; }
public RateInfos RateInfos { get; set; }
public RoomImages RoomImages { get; set; }
public ValueAdds ValueAdds { get; set; }
public string deepLink { get; set; }
public int minGuestAge { get; set; }
public int propertyId { get; set; }
public int quotedOccupancy { get; set; }
public int rateCode { get; set; }
public string rateDescription { get; set; }
public int rateOccupancyPerRoom { get; set; }
public int roomTypeCode { get; set; }
public string roomTypeDescription { get; set; }
public string smokingPreferences { get; set; }
public string supplierType { get; set; }
}
public class HotelRoomAvailabilityResponse
{
public List<HotelRoomResponse> HotelRoomResponse { get; set; }
public string arrivalDate { get; set; }
public string checkInInstructions { get; set; }
public string customerSessionId { get; set; }
public string departureDate { get; set; }
public string hotelAddress { get; set; }
public string hotelCity { get; set; }
public string hotelCountry { get; set; }
public int hotelId { get; set; }
public string hotelName { get; set; }
public string hotelStateProvince { get; set; }
public int numberOfRoomsRequested { get; set; }
public int size { get; set; }
public decimal tripAdvisorRating { get; set; }
public string tripAdvisorRatingUrl { get; set; }
public int tripAdvisorReviewCount { get; set; }
}
public class ExpediaHotelRoomAvailability
{
public HotelRoomAvailabilityResponse HotelRoomAvailabilityResponse { get; set; }
}
}
Could this possibly have something to do with the # symbols in the JSON and if so how do I get around this?
You can handle the # symbols named fields by providing their name using a [DataMember(Name=...)] attribute.
Unfortunately this mean you have to provide a [DataContract] attribute on your DTO, which means all the properties then become opt-in. So all properties will need to have [DataMember] to be included, which makes the DTO less readable.
So your NightlyRate DTO becomes:
[DataContract]
public class NightlyRate
{
[DataMember(Name="#baseRate")]
public string baseRate { get; set; }
[DataMember(Name="#promo")]
public string promo { get; set; }
[DataMember(Name="#rate")]
public string rate { get; set; }
}
And NightlyRatesPerRoom would be:
[DataContract]
public class NightlyRatesPerRoom
{
[DataMember]
public List<NightlyRate> NightlyRate { get; set; }
[DataMember(Name="#size")]
public int size { get; set; }
}
Obviously you will have to mark up the other DTOs as appropriate. I hope that helps.
I am trying to generate C# class using the JSON string from here http://json2csharp.com/ this works fine. But I can't parse the JSON to the object generated by the website.
Here is the JSON string
{
"searchParameters":{
"key":"**********",
"system":"urn:oid:.8"
},
"message":" found one Person matching your search criteria.",
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person?key=123456&system=12.4.34.."
}
},
"_embedded":{
"person":[
{
"details":{
"address":[
{
"line":["5554519 testdr"],
"city":"testland",
"state":"TT",
"zip":"12345",
"period":{
"start":"2003-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"name":[
{
"use":"usual",
"family":["BC"],
"given":["TWO"],
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"gender":{
"code":"M",
"display":"Male"
},
"birthDate":"9999-02-03T00:00:00Z",
"identifier":[
{
"use":"unspecified",
"system":"urn:oid:2.19.8",
"key":"",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"telecom":[
{
"system":"email",
"value":"test#test.com",
"use":"unspecified",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"photo":[
{
"content":{
"contentType":"image/jpeg",
"language":"",
"data":"",
"size":0,
"hash":"",
"title":"My Picture"
}
}
]
},
"enrolled":true,
"enrollmentSummary":{
"dateEnrolled":"9999-02-07T21:39:11.174Z",
"enroller":"test Support"
},
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc"
},
"unenroll":{
"href":"https://integration.rest.api.test.com/v1/person/1b018dc4-182d-4296-90cc-/unenroll"
},
"personLink":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc-953c/personLink"
},
"personMatch":{
"href":"https://integration.rest.api.commonwellalliance.org/v1/person/-182d-4296-90cc-/personMatch?orgId="
}
}
}
]
}
}
Here is the code I use to convert to the object.
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (PersonsearchVM)js.Deserialize(jsonstr, typeof(PersonsearchVM));
Is there any other wat to generate the object and parse?
I think you have some invalid characters in your JSON string. Run it through a validator and add the necessary escape characters.
http://jsonlint.com/
You aren't casting it to the right object. Cast it to the type RootObject.
Eg
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (RootObject)js.Deserialize(jsonstr, typeof(RootObject));
The code that json 2 csharp creates is this:
public class SearchParameters
{
public string key { get; set; }
public string system { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class LinKs
{
public Self self { get; set; }
}
public class Period
{
public string start { get; set; }
public string end { get; set; }
}
public class Address
{
public List<string> line { get; set; }
public string city { get; set; }
public string __invalid_name__state { get; set; }
public string zip { get; set; }
public Period period { get; set; }
}
public class PerioD2
{
public string start { get; set; }
public string end { get; set; }
}
public class Name
{
public string use { get; set; }
public List<string> family { get; set; }
public List<string> given { get; set; }
public PerioD2 __invalid_name__perio
d { get; set; }
}
public class Gender
{
public string __invalid_name__co
de { get; set; }
public string display { get; set; }
}
public class Period3
{
public string start { get; set; }
public string __invalid_name__end { get; set; }
}
public class Identifier
{
public string use
{ get; set; }
public string system { get; set; }
public string key { get; set; }
public Period3 period { get; set; }
}
public class Period4
{
public string start { get; set; }
public string end { get; set; }
}
public class Telecom
{
public string system { get; set; }
public string value { get; set; }
public string use { get; set; }
public Period4 period { get; set; }
}
public class Content
{
public string contentType { get; set; }
public string language { get; set; }
public string __invalid_name__dat
a { get; set; }
public int size { get; set; }
public string hash { get; set; }
public string title { get; set; }
}
public class Photo
{
public Content content { get; set; }
}
public class Details
{
public List<Address> address { get; set; }
public List<Name> name { get; set; }
public Gender gender { get; set; }
public string birthDate { get; set; }
public List<Identifier> identifier { get; set; }
public List<Telecom> telecom { get; set; }
public List<Photo> photo { get; set; }
}
public class EnrollmentSummary
{
public string dateEnrolled { get; set; }
public string __invalid_name__en
roller { get; set; }
}
public class Self2
{
public string href { get; set; }
}
public class UnEnroll
{
public string href { get; set; }
}
public class PersonLink
{
public string href { get; set; }
}
public class PersonMatch
{
public string href { get; set; }
}
public class Links2
{
public Self2 self { get; set; }
public UnEnroll __invalid_name__un
enroll { get; set; }
public PersonLink personLink { get; set; }
public PersonMatch personMatch { get; set; }
}
public class Person
{
public Details details { get; set; }
public bool __invalid_name__e
nrolled { get; set; }
public EnrollmentSummary enrollmentSummary { get; set; }
public Links2 _links { get; set; }
}
public class Embedded
{
public List<Person> person { get; set; }
}
public class RootObject
{
public SearchParameters searchParameters { get; set; }
public string message { get; set; }
public LinKs __invalid_name___lin
ks { get; set; }
public Embedded _embedded { get; set; }
}
The following function will convert JSON into a C# class where T is the class type.
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms); //
return obj;
}
}
You need a reference to the System.Runtime.Serialization.json namespace.
The function is called in the following manner;
calendarList = Deserialise<GoogleCalendarList>(calendarListString);
calendarlist being the C# class and calendarListString the string containing the JSON.