Deserealization not working properly - c#

I've create a class for deserialize this JSON
public class Self
{
public string href { get; set; }
}
public class Team
{
public string href { get; set; }
}
public class Links
{
public Self _self { get; set; }
public Team team { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public string position { get; set; }
public int jerseyNumber { get; set; }
public string dateOfBirth { get; set; }
public string nationality { get; set; }
public string contractUntil { get; set; }
public string marketValue { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public int count { get; set; }
public List<Player> players { get; set; }
}
public struct Player_Struct
{
public string id;
public string name;
public string position;
public int jerseyNumber;
public string dateOfBirth;
public string nationality;
public string contractUntil;
public string marketValue;
}
So I made a function to create an HttpRequest and the relative object:
string requestUrl = teams.link_teams;
string responseText = parser.Request(requestUrl);
var obj = JsonConvert.DeserializeObject<Players.RootObject>(responseText);
Now the problem's that the compiler return this exception:
Unhandled exception 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll
Ulteriori informazioni: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SF_DebugProject.API.Players+Links' 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.
Path '_links', line 1, position 11.
So with the fix hint I've tried to repair the error change the object into:
List<Players.RootObject> obj = JsonConvert.DeserializeObject<List<Players.RootObject>>(responseText);
but in this way I can't see any attribute of the rootobject when I do the foreach. What I doing wrong?

From what I understand you want to deserialize a JSON string in a RootObject that contains a list of players.
The classes should look like this:
public class Rootobject
{
public _Links _links { get; set; }
public int count { get; set; }
public Player[] players { get; set; }
}
public class _Links
{
public _Self _self { get; set; }
public Team team { get; set; }
}
public class _Self
{
public string href { get; set; }
}
public class Team
{
public string href { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public string position { get; set; }
public int jerseyNumber { get; set; }
public string dateOfBirth { get; set; }
public string nationality { get; set; }
public string contractUntil { get; set; }
public string marketValue { get; set; }
}
So what you should do is something like the following :
var obj = JsonConvert.DeserializeObject<RootObject>(response);
foreach(var player in obj.players)
{
// some stuff
}

Related

Cannot deserialize the current JSON object into type because the type requires a JSON array

I am new to JSON string handling in C# and have the following error when trying to deserialize a JSON string:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Formula1Info.Models.clsMRData]' 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<T>) 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 'MRData.xmlns', line 1, position 19.
The JSON string is:
{"MRData":{"xmlns":"http:\/\/ergast.com\/mrd\/1.5","series":"f1","url":"http://ergast.com/api/f1/1952.json","limit":"30","offset":"0","total":"8","RaceTable":{"season":"1952","Races":[{"season":"1952","round":"1","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Swiss_Grand_Prix","raceName":"Swiss Grand Prix","Circuit":{"circuitId":"bremgarten","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_Bremgarten","circuitName":"Circuit Bremgarten","Location":{"lat":"46.9589","long":"7.40194","locality":"Bern","country":"Switzerland"}},"date":"1952-05-18"},{"season":"1952","round":"2","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Indianapolis_500","raceName":"Indianapolis 500","Circuit":{"circuitId":"indianapolis","url":"http:\/\/en.wikipedia.org\/wiki\/Indianapolis_Motor_Speedway","circuitName":"Indianapolis Motor Speedway","Location":{"lat":"39.795","long":"-86.2347","locality":"Indianapolis","country":"USA"}},"date":"1952-05-30"},{"season":"1952","round":"3","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Belgian_Grand_Prix","raceName":"Belgian Grand Prix","Circuit":{"circuitId":"spa","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_de_Spa-Francorchamps","circuitName":"Circuit de Spa-Francorchamps","Location":{"lat":"50.4372","long":"5.97139","locality":"Spa","country":"Belgium"}},"date":"1952-06-22"},{"season":"1952","round":"4","url":"http:\/\/en.wikipedia.org\/wiki\/1952_French_Grand_Prix","raceName":"French Grand Prix","Circuit":{"circuitId":"essarts","url":"http:\/\/en.wikipedia.org\/wiki\/Rouen-Les-Essarts","circuitName":"Rouen-Les-Essarts","Location":{"lat":"49.3306","long":"1.00458","locality":"Rouen","country":"France"}},"date":"1952-07-06"},{"season":"1952","round":"5","url":"http:\/\/en.wikipedia.org\/wiki\/1952_British_Grand_Prix","raceName":"British Grand Prix","Circuit":{"circuitId":"silverstone","url":"http:\/\/en.wikipedia.org\/wiki\/Silverstone_Circuit","circuitName":"Silverstone Circuit","Location":{"lat":"52.0786","long":"-1.01694","locality":"Silverstone","country":"UK"}},"date":"1952-07-19"},{"season":"1952","round":"6","url":"http:\/\/en.wikipedia.org\/wiki\/1952_German_Grand_Prix","raceName":"German Grand Prix","Circuit":{"circuitId":"nurburgring","url":"http:\/\/en.wikipedia.org\/wiki\/N%C3%BCrburgring","circuitName":"Nürburgring","Location":{"lat":"50.3356","long":"6.9475","locality":"Nürburg","country":"Germany"}},"date":"1952-08-03"},{"season":"1952","round":"7","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Dutch_Grand_Prix","raceName":"Dutch Grand Prix","Circuit":{"circuitId":"zandvoort","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_Zandvoort","circuitName":"Circuit Park Zandvoort","Location":{"lat":"52.3888","long":"4.54092","locality":"Zandvoort","country":"Netherlands"}},"date":"1952-08-17"},{"season":"1952","round":"8","url":"http:\/\/en.wikipedia.org\/wiki\/1952_Italian_Grand_Prix","raceName":"Italian Grand Prix","Circuit":{"circuitId":"monza","url":"http:\/\/en.wikipedia.org\/wiki\/Autodromo_Nazionale_Monza","circuitName":"Autodromo Nazionale di Monza","Location":{"lat":"45.6156","long":"9.28111","locality":"Monza","country":"Italy"}},"date":"1952-09-07"}]}}}
and I deserialize this via this code:
var jF1Season = JsonConvert.DeserializeObject<Root>(strJSON);
The class structure is:
public class Root
{
public List<clsMRData> MRData { get; set; }
}
public class clsMRData
{
public string xmlns { get; set; }
public string series { get; set; }
public string url { get; set; }
public string limit { get; set; }
public string offset { get; set; }
public string total { get; set; }
public List<clsRaceTable> RaceTable { get; set; }
}
public class clsRaceTable
{
public string season { get; set; }
public List<clsRace> Races { get; set; }
}
public class clsRace
{
public string season { get; set; }
public string round { get; set; }
public string url { get; set; }
public string raceName { get; set; }
public List<clsCircuit> Circuit { get; set; }
public string date { get; set; }
public string time { get; set; }
}
public class clsCircuit
{
public string circuitId { get; set; }
public string url { get; set; }
public string circuitName { get; set; }
public List<clsLocation> Location { get; set; }
}
public class clsLocation
{
public string lat { get; set; }
[JsonProperty(PropertyName = "Root.MRData.RaceTable.Races.Circuit.Location.long")]
public string lon { get; set; }
public string locality { get; set; }
public string country { get; set; }
}
I guess the error is relating to how I have set this structure up, but cannot see why, so any help in solving this error would be appreciated.
you have several bugs in your code.Replace List<clsRaceTable> , List<clsCircuit> , List<clsLocation> with clsRaceTable,clsCircuit and clsLocation. Your classes should be
public class Root
{
public clsMRData MRData { get; set; }
}
public class clsMRData
{
public string xmlns { get; set; }
public string series { get; set; }
public string url { get; set; }
public string limit { get; set; }
public string offset { get; set; }
public string total { get; set; }
public clsRaceTable RaceTable { get; set; }
}
public class clsRaceTable
{
public string season { get; set; }
public List<clsRace> Races { get; set; }
}
public class clsRace
{
public string season { get; set; }
public string round { get; set; }
public string url { get; set; }
public string raceName { get; set; }
public clsCircuit Circuit { get; set; }
public string date { get; set; }
public string time { get; set; }
}
public class clsCircuit
{
public string circuitId { get; set; }
public string url { get; set; }
public string circuitName { get; set; }
public clsLocation Location { get; set; }
}
public class clsLocation
{
public string lat { get; set; }
[JsonProperty(PropertyName = "long")]
public string lon { get; set; }
public string locality { get; set; }
public string country { get; set; }
}

Json Deserialization | Cannot Deserialize Current Json

I have below Json -
{"property_id":"53863730","name":"Hayat Elhamra","address":{"line_1":"Jeddah","city":"Jeddah","state_province_name":"Jeddah","postal_code":"23212","country_code":"SA","obfuscation_required":false,"localized":{"links":{"ar-SA":{"method":"GET","href":"https://api.ean.com/2.4/properties/content?language=ar-SA&property_id=53863730&include=address"}}}},"location":{"coordinates":{"latitude":21.520902,"longitude":39.158265}},"phone":"20-01145772035","category":{"id":"16","name":"Apartment"},"rank":99999999,"business_model":{"expedia_collect":true,"property_collect":true},"dates":{"added":"2020-06-10T23:03:21.345Z","updated":"2020-06-10T23:03:23.701Z"},"chain":{"id":"0","name":"Independent"},"brand":{"id":"0","name":"Independent"}}
{"property_id":"53183065","name":"Carefully Furnished Bungalow With 2 Bathrooms, 7km From Pula","address":{"line_1":"1 x M 90,3","line_2":"PRIVATE_VACATION_HOME 3","city":"Fazana","state_province_name":"Istria (county)","postal_code":"52212","country_code":"HR","obfuscation_required":true,"localized":{"links":{"hr-HR":{"method":"GET","href":"https://api.ean.com/2.4/properties/content?language=hr-HR&property_id=53183065&include=address"}}}},"ratings":{"property":{"rating":"3.0","type":"Star"}},"location":{"coordinates":{"latitude":44.93,"longitude":13.8}},"phone":"410442743080","category":{"id":"17","name":"Private vacation home"},"rank":99999999,"business_model":{"expedia_collect":true,"property_collect":false},"dates":{"added":"2020-05-13T21:06:42.861Z","updated":"2020-05-18T21:57:39.242Z"},"statistics":{"1073743378":{"id":"1073743378","name":"Number of bedrooms - 2","value":"2"},"1073743380":{"id":"1073743380","name":"Max occupancy - 4","value":"4"},"1073743379":{"id":"1073743379","name":"Number of bathrooms - 2","value":"2"}},"chain":{"id":"7278","name":"Belvilla"},"brand":{"id":"7353","name":"Belvilla"}}
{"property_id":"53182898","name":"Snug Cottage in Pašman With Roofed Terrace","address":{"line_1":"Pasman","city":"Pasman","state_province_name":"Zadar","postal_code":"23260","country_code":"HR","obfuscation_required":true,"localized":{"links":{"hr-HR":{"method":"GET","href":"https://api.ean.com/2.4/properties/content?language=hr-HR&property_id=53182898&include=address"}}}},"ratings":{"property":{"rating":"1.0","type":"Star"}},"location":{"coordinates":{"latitude":43.891571,"longitude":15.423619}},"phone":"410442743080","category":{"id":"11","name":"Cottage"},"rank":99999999,"business_model":{"expedia_collect":true,"property_collect":false},"dates":{"added":"2020-05-13T21:13:49.155Z","updated":"2020-05-27T21:02:31.808Z"},"statistics":{"1073743378":{"id":"1073743378","name":"Number of bedrooms - 2","value":"2"},"1073743380":{"id":"1073743380","name":"Max occupancy - 5","value":"5"},"1073743379":{"id":"1073743379","name":"Number of bathrooms - 1","value":"1"}},"chain":{"id":"7278","name":"Belvilla"},"brand":{"id":"7353","name":"Belvilla"}}
For this I have created below class structure -
public class Property
{
public string property_id { get; set; }
public string name { get; set; }
public Address address { get; set; }
public Location location { get; set; }
public string phone { get; set; }
public Category category { get; set; }
public int rank { get; set; }
public Business_Model business_model { get; set; }
public Dates dates { get; set; }
public Chain chain { get; set; }
public Brand brand { get; set; }
}
public class Address
{
public string line_1 { get; set; }
public string city { get; set; }
public string state_province_name { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
public bool obfuscation_required { get; set; }
public Localized localized { get; set; }
}
public class Localized
{
public Links links { get; set; }
}
public class Links
{
public ArSA arSA { get; set; }
}
public class ArSA
{
public string method { get; set; }
public string href { get; set; }
}
public class Location
{
public Coordinates coordinates { get; set; }
}
public class Coordinates
{
public float latitude { get; set; }
public float longitude { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
}
public class Business_Model
{
public bool expedia_collect { get; set; }
public bool property_collect { get; set; }
}
public class Dates
{
public DateTime added { get; set; }
public DateTime updated { get; set; }
}
public class Chain
{
public string id { get; set; }
public string name { get; set; }
}
public class Brand
{
public string id { get; set; }
public string name { get; set; }
}
I have below code where I am getting error -
using (StreamReader streamReader = new StreamReader("d://propertycontent.expediacollect.en-US.json"))
{
using (var json = new JsonTextReader(streamReader))
{
JsonSerializer serializer = new JsonSerializer();
var properties= (List<Property>)serializer.Deserialize(json, typeof(List<Property>));
}
}
Error -
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Property]' 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<T>) 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 'property_id', line 1, position 15.'
It is not deserializing because it is not valid json. To make it valid, and to make it a List<Property> add [ to the beginning of the json and ] to the end of the json. Just enclose the json in [ ... ] to make it valid and it will deserialize assuming the rest of it is valid and is not missing any commas or brackets.
try this, you will have to install NewtonsoftJson. It was tested using Visual Studio and Postman and works properly.
var jsonOrig= ...your json
var json = JsonConvert.SerializeObject(jsonOrig);
var jsonObj = JsonConvert.DeserializeObject<DataRoot>(json);
classes
public class DataRoot
{
public string property_id { get; set; }
public string name { get; set; }
public Address address { get; set; }
public Location location { get; set; }
public string phone { get; set; }
public Category category { get; set; }
public int rank { get; set; }
public BusinessModel business_model { get; set; }
public Dates dates { get; set; }
public Chain chain { get; set; }
public Brand brand { get; set; }
}
public class ArSA
{
public string method { get; set; }
public string href { get; set; }
}
public class Links
{
[JsonProperty("ar-SA")]
public ArSA ArSA { get; set; }
}
public class Localized
{
public Links links { get; set; }
}
public class Address
{
public string line_1 { get; set; }
public string city { get; set; }
public string state_province_name { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
public bool obfuscation_required { get; set; }
public Localized localized { get; set; }
}
public class Coordinates
{
public double latitude { get; set; }
public double longitude { get; set; }
}
public class Location
{
public Coordinates coordinates { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
}
public class BusinessModel
{
public bool expedia_collect { get; set; }
public bool property_collect { get; set; }
}
public class Dates
{
public DateTime added { get; set; }
public DateTime updated { get; set; }
}
public class Chain
{
public string id { get; set; }
public string name { get; set; }
}
public class Brand
{
public string id { get; set; }
public string name { get; set; }
}
`````

Parsing JSON With Newtonsoft Throwing Incorrect Format Error

I am attempting to parse my JSON response by taking the response and copy/paste it into Json2CSharp then adding the 2 newly generated classes to the bottom of my current class. (I do not like dealing with multiple classes). The issue that I am having is that when I attempt to access the generated class RootObject I get an error of
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Test.RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Even though the syntax was converted for me, and I did not change it. What do I need to alter so that this becomes valid workable syntax?
static void Main(string[] args)
{
string userid= "186exa";
var url = "https/?rst=" + userid;
var connectionClient = new WebClient();
connectionClient.Headers.Set("H", "XXXXXXXXXXXX");
connectionClient.Headers.Set("uname", "user");
connectionClient.Headers.Set("pswd", "pwd");
var content = connectionClient.DownloadString(url);
}
EDITThis is the class - will post the JSON shortly
public class List
{
public int id { get; set; }
public string cmu { get; set; }
public int lno { get; set; }
public string clr { get; set; }
public string name { get; set; }
public string origin { get; set; }
public string MajorStyle { get; set; }
public string Style { get; set; }
public string styleImage { get; set; }
public int hid { get; set; }
public string bqty { get; set; }
public int cask { get; set; }
public int local { get; set; }
public string city { get; set; }
}
public class RootObject
{
public string style { get; set; }
public List<List> List { get; set; }
}
This is the retunred JSON
[{"Style":"Cajun","List":[{"id":1225,"cmu":"41.2","lno":10,"name":"Bear","origin":"Lake Sinclair, MO","MajorStyle":"Burn Yo Bottom","Style":"","styleImage":"","hid":1,"bqty":"1.00","cask":0,"local":0,"city":"Amsterdam"}
There are two things at fault with the code you have posted,
The property "clr" does not exist in the JSON.
The JSON ends prematurely, it should have ]}] on the end to be correct.
Fixing both of those issues, the code parses correctly in Newtonsoft when passing it the type RootObject[], as per:
var o = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject[]>(s);
Where s is the JSON string.
First, you need your classes match with your JSON response, so your classes should look like
public class RootObject
{
public string Style { get; set; }
public List[] List { get; set; }
}
public class List
{
public int id { get; set; }
public string cmu { get; set; }
public int lno { get; set; }
public string clr { get; set; }
public string name { get; set; }
public string origin { get; set; }
public string MajorStyle { get; set; }
public string Style { get; set; }
public string styleImage { get; set; }
public int hid { get; set; }
public string bqty { get; set; }
public int cask { get; set; }
public int local { get; set; }
public string city { get; set; }
}
After that you need to map the response to an object
using Newtonsoft.Json; // Need this to work with JsonConvert
string json = #"[
{
'Style':'Cajun',
'List':
[
{
'id':1225,
'cmu':'41.2',
'lno':10,
'name':'Bear',
'origin':'Lake Sinclair, MO',
'MajorStyle':'Burn Yo Bottom',
'Style':'',
'styleImage':'',
'hid':1,
'bqty':'1.00',
'cask':0,
'local':0,
'city':'Amsterdam'
}
]
}
]";
RootObject[] response = JsonConvert.DeserializeObject<RootObject[]>(json);
Using the keyword List could lead you to mistakes, because there is also a class for C# called List, so be careful.

Linq transformation help needed

I've got a List of this object:
public class WebinarAttendeesList {
public int wa_id { get; set; }
public int PID { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string JoinTime { get; set; }
public string TimeInSession { get; set; }
public string LeaveTime { get; set; }
public int FirstPollCount { get; set; }
public int SecondPollCount { get; set; }
public int AttendedWebinar { get; set; }
public int Makeup { get; set; }
public string Comments { get; set; }
public string RegistrantKey { get; set; }
public string webinarKey { get; set; }
}
I'm using this Linq code:
var webinars = new
{
Webinars = r.GroupBy(x => new { x.PID, x.FullName }).
Select(y => new
{
PID = y.Key.PID,
FullName = y.Key.FullName,
AffReceived = 0,
Attendances = y.Select(z => new
{
WebinarKey = z.webinarKey,
RegistrantKey = z.RegistrantKey,
TimeInSession = z.TimeInSession,
FirstPollCount = z.FirstPollCount,
SecondPollCount = z.SecondPollCount,
AttendedWebinar = z.AttendedWebinar
})
})
};
string json = JsonConvert.SerializeObject(webinars);
to transform the List to JSON. But, I think I'd rather
have it transformed into a List<FinalWebinarAttendeesList> (see below
definition). The JSON that it produces looks correct and passes lint.
When I try to do this:
List<FinalWebinarAttendeesList> fl = JsonConvert.DeserializeObject<List<FinalWebinarAttendeesList>>(json);
I get an error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[WebinarProject.Models.FinalWebinarAttendeesList]'
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<T>)
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
'Webinars', line 1, position 12.
How can I either transform this directly into the object I want, or be able to deserialize it into the object I want?
FinalWebinarAttendeesList definition:
public class FinalWebinarAttendeesList
{
public FinalWebinar Webinars {get; set; }
}
public class FinalWebinar
{
public int PtID { get; set; }
public string FullName { get; set; }
public int AffReceived { get; set; }
public List<FinalWebinarAttendee> Attendances { get; set; }
}
public class FinalWebinarAttendee
{
public string RegistrantKey { get; set; }
public string TimeInSession { get; set; }
public int FirstPollCount { get; set; }
public int SecondPollCount { get; set; }
public int AttendedWebinar { get; set; }
}
I created a json sample output using random data and and I found that you are trying to deserialize the json with the wrong object.
Json output:
{"Webinars":[{"PID":453,"FullName":"jdis","Attendances":[{"WebinarKey":"kdnsaod","RegistrantKey":"udhaso","TimeInSession":"hdija","FirstPollCount":45,"SecondPollCount":45,"AttendedWebinar":0}]}]}
The object has de following structure:
public class Attendance
{
public string WebinarKey { get; set; }
public string RegistrantKey { get; set; }
public string TimeInSession { get; set; }
public int FirstPollCount { get; set; }
public int SecondPollCount { get; set; }
public int AttendedWebinar { get; set; }
}
public class Webinar
{
public int PID { get; set; }
public string FullName { get; set; }
public List<Attendance> Attendances { get; set; }
}
public class RootObject
{
public List<Webinar> Webinars { get; set; }
}
And for Deserializing the object:
var result = JsonConvert.DeserializeObject<RootObject>(json);
You created only one Webinar instance, but you are trying to deserialize a list of Webinars. Try:
FinalWebinarAttendeesList fl = JsonConvert.DeserializeObject<FinalWebinarAttendeesList>(json);

How to parse / deserialize JSON returned from rest service in C#

I am getting JSON in string format from a URL whose structure is like this, but I am unable to parse it. It's throwing an exception, any idea how to parse it?
Here is the structure:
{
"pathway":{
"patients":{
"patient":[
{
"patientid":"7703176",
"name":"Abbot, Bud",
"status":"Invited",
"start":"2013-12-07",
"last":"N/A",
"engagement":"N/A",
"drug":"N/A",
"adherence":"N/A",
"vitals":"Current",
"last_appointment":"2013-10-25",
"next_appointment":"None"
},
{
"patientid":"5089554",
"name":"Brennan, Bonnie",
"status":"Connected",
"start":"2013-12-29",
"last":"2014-02-01",
"engagement":"Low",
"drug":" ",
"adherence":" ",
"vitals":"Out of Date",
"last_appointment":"2013-04-21",
"next_appointment":"None"
}
]
}
}
}
i am doing like this:
public class PathWayWrapper
{
public pathway pathway { get; set; }
}
and
public class pathway
{
public List<patient> patients { get; set; }
}
and
public class patient
{
public long patientid { get; set; }
public string name { get; set; }
public string status { get; set; }
public string start { get; set; }
public string last { get; set; }
public string engagement { get; set; }
public string drug { get; set; }
public string adherence { get; set; }
public string vitals { get; set; }
public string last_appointment { get; set; }
public string next_appointment { get; set; }
}
here is my parsing code:
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
var Jsonobject = JsonConvert.DeserializeObject<PathWayWrapper>(json);
objPathway = Jsonobject.pathway;
The classes into which you're deserializing are incorrect. You are missing the "Patients" class.
When I have JSON and am trying to deserialize it I like to use http://json2csharp.com to generate a first cut at the deserialization classes. It's more accurate than trying to do it by hand.
var jsonobject = JsonConvert.DeserializeObject<RootObject>(json);
public class Patient
{
public string patientid { get; set; }
public string name { get; set; }
public string status { get; set; }
public string start { get; set; }
public string last { get; set; }
public string engagement { get; set; }
public string drug { get; set; }
public string adherence { get; set; }
public string vitals { get; set; }
public string last_appointment { get; set; }
public string next_appointment { get; set; }
}
public class Patients
{
public List<Patient> patient { get; set; }
}
public class Pathway
{
public Patients patients { get; set; }
}
public class RootObject
{
public Pathway pathway { get; set; }
}
P.S. The exception you were getting is usually a really good clue that there's something wrong with the way you've defined the deserialization classes.
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ConsoleApplication1.Program+patient]' 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.

Categories

Resources