I have the following class
public class CallbackResultsJson
{
public class CallbackResults
{
public string Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
public string Log { get; set; }
public string StatusText { get; set; }
public string TransactionToken { get; set; }
}
}
I am trying to use Json.Net to Deserialize requestbody but I am always getting a null for status,data. any ideas why ?
var requestbody =#"
{
"CallbackResults":
{
"TransactionToken":"b65524-qwe",
"Status":0,
"Message":"Publish Application to QaLevel Operation Completed",
"Data":[],
"Log":["sucess"
},
"RequestNumber":"REQ1234"
}"
var TransactionResult = JsonConvert.DeserializeObject<CallbackResultsJson.CallbackResults>(requestBody);
Just a little bit of change should be done.
Your class:
public class CallbackResultsJson
{
public CallbackResultsClass CallbackResults { get; set; }
public string RequestNumber { get; set; }
public class CallbackResultsClass
{
public int Status { get; set; }
public string Message { get; set; }
public string[] Data { get; set; }
public string Log { get; set; }
public string TransactionToken { get; set; }
}
}
Your data:
var requestbody = #"
{
""CallbackResults"":
{
""TransactionToken"":""b65524-qwe"",
""Status"":0,
""Message"":""Publish Application to QaLevel Operation Completed"",
""Data"":[""Data1"", ""Data2""],
""Log"":""sucess""
},
""RequestNumber"":""REQ1234""
}";
var result = JsonConvert.DeserializeObject<CallbackResultsJson>(requestbody);
Your class needs to have a property of the sub-type,
public class CallbackResultsJson
{
public CallBackResults CallbackResults { get; set; }
public string RequestNumber { get; set; )
public class CallbackResults
{
public string Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
public string Log { get; set; }
public string StatusText { get; set; }
public string TransactionToken { get; set; }
}
}
var result = JsonConvert.DeserializeObject<CallbackResultsJson>(requestBody);
I have used json2csharp.com to convert requestbody to c# classes and it generated these classes.it worked
public class CallbackResults
{
public string TransactionToken { get; set; }
public int Status { get; set; }
public string Message { get; set; }
public List<string> Data { get; set; }
public List<string> Log { get; set; }
}
public class CallbackResultsRootObj
{
public CallbackResults VdiCallbackResults { get; set; }
public string RequestNumber { get; set; }
}
var vdiTransactionResult = JsonConvert.DeserializeObject<CallbackResultsRootObj>(requestBody);
Related
I faced the problem: Cannot deserialize the current JSON object.
As follows:
public List<Track> Tracks { get; set; }
public async Task<List<Track>> GetTracking()
{
using (var httpClient = new HttpClient())
{
using (var requests = new HttpRequestMessage(new HttpMethod("GET"), "urlxxxxxxxx..."))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
requests.Headers.TryAddWithoutValidation("accept", "application/json");
var response = await httpClient.SendAsync(requests);
using (HttpContent content = response.Content)
{
var jsonStr = content.ReadAsStringAsync().GetAwaiter().GetResult();
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr); //Get Error**
Tracks = res;
}
}
}
return Tracks;
}
Model Class
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferences> documentReferences { get; set; }
public TransportCall transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public LocationMearsk location { get; set; }
public VesselMearsk vessel { get; set; }
}
My input data:
https://drive.google.com/file/d/12g0nHkHlmbU4Af8crHlzKXD_ERIZdCyH/view?usp=sharing
As in my description. I get the error: I get the error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[XX. Models.Track]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Even though I declared: public List events { get; set; }
Is the problem I have misunderstood the format of DeserializeObject. Looking forward to everyone's help. Thank
you have an object, not an array
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
and fix class
public class Events
{
....
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
Your model is incomplete and has typos. Assuming you have the correct versions of them.
You are doing:
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr);
which should be just:
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
Your json doesn't have an array at the root level.
Full working sample:
void Main()
{
var res = JsonConvert.DeserializeObject<Track>(myJson);
}
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public Location location { get; set; }
public Vessel vessel { get; set; }
}
public partial class Location
{
public string LocationName { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string UnLocationCode { get; set; }
public string FacilityCode { get; set; }
public string FacilityCodeListProvider { get; set; }
}
public partial class Vessel
{
public long VesselImoNumber { get; set; }
public string VesselName { get; set; }
public string VesselFlag { get; set; }
public string VesselCallSignNumber { get; set; }
public string VesselOperatorCarrierCode { get; set; }
public string VesselOperatorCarrierCodeListProvider { get; set; }
}
static readonly string myJson = #"{
""events"": [
{
""eventID"": ""6832920321"",
""eventType"": ""SHIPMENT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""shipmentEventTypeCode"": ""DRFT"",
""documentTypeCode"": ""SHI"",
""documentID"": ""205284917""
},
{
""eventID"": ""6832920321"",
""eventType"": ""TRANSPORT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""transportEventTypeCode"": ""ARRI"",
""documentReferences"": [
{
""documentReferenceType"": ""BKG"",
""documentReferenceValue"": ""ABC123123123""
},
{
""documentReferenceType"": ""TRD"",
""documentReferenceValue"": ""85943567-eedb-98d3-f4ed-aed697474ed4""
}
],
""transportCall"": {
""transportCallID"": ""123e4567-e89b-12d3-a456-426614174000"",
""carrierServiceCode"": ""FE1"",
""exportVoyageNumber"": ""2103S"",
""importVoyageNumber"": ""2103N"",
""transportCallSequenceNumber"": 2,
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG"",
""facilityTypeCode"": ""POTE"",
""otherFacility"": ""Balboa Port Terminal, Avenida Balboa Panama"",
""modeOfTransport"": ""VESSEL"",
""location"": {
""locationName"": ""Eiffel Tower"",
""latitude"": ""48.8585500"",
""longitude"": ""2.294492036"",
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG""
},
""vessel"": {
""vesselIMONumber"": 1801323,
""vesselName"": ""King of the Seas"",
""vesselFlag"": ""DE"",
""vesselCallSignNumber"": ""NCVV"",
""vesselOperatorCarrierCode"": ""MAEU"",
""vesselOperatorCarrierCodeListProvider"": ""NMFTA""
}
}
}
]
}";
EDIT: Result is something like:
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; }
}
here is my Get Set Method Class
public class RechargeGridDTO
{
public String from { get; set; }
public String to { get; set; }
public String errormsg { get; set; }
public String status { get; set; }
public RechargeInnerMsgGridInfo message { get; set; }
public String type { get; set; }
public String reqid { get; set; }
}
public class RechargeInnerMsgGridInfo
{
public String mob {get;set;}
public String rctype { get; set; }
public String rcservice { get; set; }
public String rcmobile { get; set; }
public String rcamt { get; set; }
public String rcpin { get; set; }
public String mytxid { get; set; }
public String optxid { get; set; }
public String txid { get; set; }
public String rcstatus { get; set; }
public String rcmsg { get; set; }
public String rctime { get; set; }
public String rcbal { get; set; }
public String rcsimbal { get; set; }
public String rcremark { get; set; }
public String rcchnnl { get; set; }
}
this is the json response I wanted to parse i-e:
msg = {
"from":"nishantuser",
"to":"smpp",
"errormsg":null,
"status":"s",
"message":
{
"mob":"9999999999",
"rctype":"Rr",
"rcservice":"Aircel",
"rcmobile":"8460149820",
"rcamt":"20",
"rcpin":"1234",
"mytxid":"4850",
"optxid":GUJNishant123,
"txid":null,
"rcstatus":s,
"rcmsg":null,
"rctime":null,
"rcbal":null,
"rcsimbal":null,
"rcremark":null,
"rcchnnl":null
},
"type":"RECHARGE",
"reqid":"4850"
}
when i am parsing this json Response then getting error...
var ResponseData = JsonConvert.DeserializeObject<RechargeGridDTO>(msg);
please give me the solution how i can parse this type of Response in using JsonConvert in C#
"optxid":GUJNishant123,
"rcstatus":s,
Those parts are not valid JSON. Strings need to be quoted:
"optxid":"GUJNishant123",
"rcstatus":"s",
I'm trying to make an application that can show local TV guide trough JSON rest api C #, but has some problems with deserialization of my Json response.
i'm only intresest in the array NOW in my json call and i do not own the api service.
I get this error message:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.DLL but was not handled in user code
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TDC_Play_TV_Mobil.superclass2+Now]' 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 'now', line 1, position 7.
My function:
private HttpClient client;
public async Task<List<superclass2.Now>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync(new Uri("http://api.yousee.tv/rest/tvguide/nowandnext/"));
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(json);
var task = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<List<superclass2.Now>>(json));
var value = await task;
// List<superclass2.Now> comments = Newtonsoft.Json.JsonConvert.DeserializeObject<List<superclass2.Now>>(await json);
System.Diagnostics.Debug.WriteLine("Comments er lavet");
return value;
}
else
{
throw new Exception("Errorhandling message");
}
}
My class file:
public class superclass2
{
public class Logos
{
public string small { get; set; }
public string large { get; set; }
public string small_seapp { get; set; }
public string large_seapp { get; set; }
public string extralarge { get; set; }
public string super { get; set; }
public string mega { get; set; }
public string netgem { get; set; }
public string svg { get; set; }
}
public class ChannelInfo
{
public string name { get; set; }
public string shortname { get; set; }
public string logo_image_prefix { get; set; }
public Logos logos { get; set; }
public int archivedays { get; set; }
public string channelcolor { get; set; }
}
public class FormattedDate
{
public string time_begin { get; set; }
public string time_end { get; set; }
public string date { get; set; }
}
public class ImagesSixteenbynine
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class ImagesFourbythree
{
public string large { get; set; }
public string small { get; set; }
}
public class ImagesSquare
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class Now
{
public int id { get; set; }
public int dvb_id { get; set; }
public int channel { get; set; }
public ChannelInfo channel_info { get; set; }
public string orgtitle { get; set; }
public string cast { get; set; }
public string directors { get; set; }
public string series_info { get; set; }
public int series_id { get; set; }
public string series_name { get; set; }
public bool allowseriesrecording { get; set; }
public int totalinarchive { get; set; }
public int popularity_score { get; set; }
public int totalupcoming { get; set; }
public int category { get; set; }
public int subcategory { get; set; }
public string category_string { get; set; }
public string subcategory_string { get; set; }
public int begin { get; set; }
public object actual_begin { get; set; }
public int end { get; set; }
public int actual_end { get; set; }
public int tvdate { get; set; }
public FormattedDate formatted_date { get; set; }
public string title { get; set; }
public string description { get; set; }
public bool archive { get; set; }
public bool scrubbingallowed { get; set; }
public int expiresfromarchive { get; set; }
public bool startover { get; set; }
public string imageprefix { get; set; }
public ImagesSixteenbynine images_sixteenbynine { get; set; }
public ImagesFourbythree images_fourbythree { get; set; }
public ImagesSquare images_square { get; set; }
public List<object> decorations { get; set; }
}
public class Logos2
{
public string small { get; set; }
public string large { get; set; }
public string small_seapp { get; set; }
public string large_seapp { get; set; }
public string extralarge { get; set; }
public string super { get; set; }
public string mega { get; set; }
public string netgem { get; set; }
public string svg { get; set; }
}
public class ChannelInfo2
{
public string name { get; set; }
public string shortname { get; set; }
public string logo_image_prefix { get; set; }
public Logos2 logos { get; set; }
public int archivedays { get; set; }
public string channelcolor { get; set; }
}
public class FormattedDate2
{
public string time_begin { get; set; }
public string time_end { get; set; }
public string date { get; set; }
}
public class ImagesSixteenbynine2
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class ImagesFourbythree2
{
public string large { get; set; }
public string small { get; set; }
}
public class ImagesSquare2
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class Next
{
public int id { get; set; }
public int dvb_id { get; set; }
public int channel { get; set; }
public ChannelInfo2 channel_info { get; set; }
public string orgtitle { get; set; }
public string cast { get; set; }
public string directors { get; set; }
public string series_info { get; set; }
public int series_id { get; set; }
public string series_name { get; set; }
public bool allowseriesrecording { get; set; }
public int totalinarchive { get; set; }
public int popularity_score { get; set; }
public int totalupcoming { get; set; }
public int category { get; set; }
public int subcategory { get; set; }
public string category_string { get; set; }
public string subcategory_string { get; set; }
public int begin { get; set; }
public int actual_begin { get; set; }
public int end { get; set; }
public int actual_end { get; set; }
public int tvdate { get; set; }
public FormattedDate2 formatted_date { get; set; }
public string title { get; set; }
public string description { get; set; }
public bool archive { get; set; }
public bool scrubbingallowed { get; set; }
public int expiresfromarchive { get; set; }
public bool startover { get; set; }
public string imageprefix { get; set; }
public ImagesSixteenbynine2 images_sixteenbynine { get; set; }
public ImagesFourbythree2 images_fourbythree { get; set; }
public ImagesSquare2 images_square { get; set; }
public List<object> decorations { get; set; }
}
public class RootObject
{
public List<Now> now { get; set; }
public List<Next> next { get; set; }
}
}
Your JSON isn't a List<superclass2.Now>, it's a superclass2.RootObject. So you need to do something like:
public async Task<List<superclass2.Now>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync(new Uri("http://api.yousee.tv/rest/tvguide/nowandnext/"));
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(json);
var task = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<superclass2.RootObject>(json));
var value = await task;
System.Diagnostics.Debug.WriteLine("Comments er lavet");
return (value == null ? null : value.now);
}
else
{
throw new Exception("Errorhandling message");
}
}
Agree with Jon Skeet it would be nicer to eliminate the nesting of classes, purely for improved readability. If you need these classes to exist only in a specific scope, it is better to use nested namespaces. They aren't causing your bug, however.
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.