Related
I have this JSON string that should be posted from JavaScript to the API:
"model": "kpi.availability",
"typeId": "kpi.availability",
"name": "Availability",
"description": "",
"version": "1.0.0",
"properties": {
"X": {
"dataType": "string",
"value": ""
},
"Y": {
"dataType": "number",
"value": 0,
"isMandatory": true
},
"Z": {
"dataType": "number",
"value": 0,
"isMandatory": true
}
}
here we have 3 properties, just for instance, but it can be more than 3 with different names.
And have this C# model which doesn't work
public class KPIType{
public string model { get; set; }
public string typeId { get; set; }
public string name { get; set; }
public string description { get; set; }
public int version { get; set; }
public IDictionary<string, PropertyItem>[] properties { get; set; }
//public List<IDictionary<string, PropertyItem>> properties { get; set; } //Didn't work
}
public class PropertyItem {
public string dataType { get; set; }
public string value { get; set; }
public bool isMandatory { get; set; }
}
But when trying to send it to the backend, it fails at the client side and I'm getting this error:
"The JSON value could not be converted to System.Collections.Generic.IDictionary`2[System.String,ABB.Advanced.Services.Management.Controllers.PropertyItem][]. Path: $.kpiType.properties | LineNumber: 0 | BytePositionInLine: 294."
This JSON is incorrect in array section. It should be like this:
{
"model": "kpi.availability",
"typeId": "kpi.availability",
"name": "Availability",
"description": "",
"version": "1.0.0",
"properties": [
{
"dataType": "string",
"value": "",
"isMandatory": true
},
{
"dataType": "number",
"value": 0,
"isMandatory": true
},
{
"dataType": "number",
"value": 0,
"isMandatory": true
}
]
}
If you want to pass objects with names into property array then you need to add "name" property to the object and then find it in your service by the name.
Exempli gratia:
"properties": [
{
"name": "A",
"dataType": "string",
"value": "",
"isMandatory": true
},
{
"name": "B",
"dataType": "number",
"value": 0,
"isMandatory": true
},
{
"name": "C",
"dataType": "number",
"value": 0,
"isMandatory": true
}
]
Two things are obvious mismatch:
Properties in C# is array, but in JSON file it is an object. Not sure what's the best to fix it, maybe best change the JSON file itself, if possible
isMandatory is bool, that is, required. However, in X it is missing. If it is optional - change it to bool?
Just remove the "[]" in front of the field "properties":
I mean use this:
public IDictionary<string, PropertyItem>[] properties { get; set; }
Replace it with:
public IDictionary<string, PropertyItem> Properties { get; set; }
I highly recommend you use a better naming convention on your class fields according to the Microsoft official
docs
NOTE: If your JSON deserialization is case sensitive you can use the [JsonProperty] attribute on your props like this:
[JsonProperty("properties")
public IDictionary<string, PropertyItem> Properties { get; set; }
public class PropertyItem
{
[JsonProperty("dataType")]
public string DataType { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("isMandatory")]
public bool IsMandatory { get; set; }
}
I'm struggling to make this conversion happen, and not sure it's entirely feasible. My JSON from a third party could look like this:
{
"equipments": [
{
"serialNumber": "11-17-053",
"equipmentType_id": "589dda4952172110008870c7",
"created": 1508856453875,
"fieldOffice_id": "594af5425fbfca00111a0c20",
"clients_id": [],
"notes": "",
"isInService": true,
"metavalues": {
"0t78nzhp9w265avlvt": {
"item_ids": [
33121
]
},
"7ogz4kehqh8h3cwip8": {
"item_ids": [
33128
]
}
},
"schedules": [],
"id": "59ef52854d40a9009c787596"
},
{
"serialNumber": "11-17-054",
"equipmentType_id": "589dda4952172110008870c7",
"created": 1508856453875,
"fieldOffice_id": "594af5425fbfca00111a0c20",
"clients_id": [],
"notes": "",
"isInService": true,
"metavalues": {
"0t78nzhp9w265avlvt": {
"item_ids": [
33121
]
},
"7ogz4kehqh8h3cwip8": {
"item_ids": [
33128
]
}
},
"schedules": [],
"id": "59ef52854d40a9009c787597"
},
{
"serialNumber": "8-17-022",
"equipmentType_id": "589dda4952172110008870c7",
"created": 1505326964589,
"fieldOffice_id": "594af5425fbfca00111a0c20",
"clients_id": [],
"notes": "",
"isInService": true,
"metavalues": {
"0t78nzhp9w265avlvt": {
"item_ids": [
33121
]
},
"7ogz4kehqh8h3cwip8": {
"item_ids": [
33128
]
}
},
"schedules": [],
"id": "59b9777480e426009d01d48d"
},
{
"serialNumber": "22A-17-001",
"equipmentType_id": "589dda4952172110008870c7",
"created": 1504908025733,
"fieldOffice_id": "58b74b080c206710004ff726",
"clients_id": [
"59bbfdf5725cd00012fb15d8"
],
"notes": "",
"isInService": true,
"metavalues": {
"0t78nzhp9w265avlvt": {
"item_ids": [
33122
]
},
"7ogz4kehqh8h3cwip8": {
"item_ids": [
33128
]
},
"g99idmcqyuo2na9e6l": "YARD",
"709pm94prt2tpjt90y": 5,
"bgen1h4i5b6f8xa1kh": "9/8/2017 7:18:24 PM",
"yvtvsl8dedudqjtdud": "0.00000, 0.00000",
"aj3h2b5fdbic9s72m3": "Parex",
"8wt1re82xidjiv8rzi": "YARD"
},
"schedules": [],
"id": "59b312f93256d5009c4a73fb"
},....
This is obviously not a complete example, but should help get my question across.
Is there a way to create a C# class that pulls in certain fields only if they exist from the "metavalues" array?
My current class is as follows which works to get the data, but not exactly how I want.
public class Equipment
{
[JsonProperty("serialNumber")]
public string SerialNumber { get; set; }
public string equipmentType_id { get; set; }
public bool isInService { get; set; }
public List<string> clients_Id { get; set; }
public string fieldOffice_id { get; set; }
[JsonProperty("id")]
public string EquipmentId { get; set; }
[JsonProperty("metavalues")]
public Dictionary<string, object> metavalues { get; set; }
}
What I'm after, is taking the key of "g99idmcqyuo2na9e6l" which is optional in the metavalues, and store it in a property called "LeaseName".
I tried the following to no avail.
public class Equipment
{
[JsonProperty("serialNumber")]
public string SerialNumber { get; set; }
public string equipmentType_id { get; set; }
public bool isInService { get; set; }
public List<string> clients_Id { get; set; }
public string fieldOffice_id { get; set; }
[JsonProperty("id")]
public string EquipmentId { get; set; }
[JsonProperty("g99idmcqyuo2na9e6l")]
public string LeaseName { get; set; }
}
If I try to make a class for the metavalues section, I get an exception indicating that JSON.NET can't convert it to my object, hence why I used the Dictionary<string, object> option.
EDIT # 1: The accepted answer works for me, but for those who stumble upon this and truly need a property name from a nested array you could try the following.
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
if (metavalues != null)
{
if (metavalues.ContainsKey("g99idmcqyuo2na9e6l"))
{
string _LeaseName = (string)metavalues["g99idmcqyuo2na9e6l"];
LeaseName = _LeaseName;
}
}
}
I think my edit approach is a bit overkill but just throwing this out there.
Yes, this is possible, but since the lease value is still one level down in the JSON you need an intermediate class to hold it (to replace the dictionary).
public class Equipment
{
...
[JsonProperty("metavalues")]
public MetaValues MetaValues { get; set; }
}
public class MetaValues
{
[JsonProperty("g99idmcqyuo2na9e6l")]
public string LeaseName { get; set; }
}
Fiddle: https://dotnetfiddle.net/Ddqzc7
I'm trying to deserialize the following JSON string in C#:
{
"class": [
"collection",
"Request"
],
"properties": {
"total_hits": 61,
"total_pages": 61,
"previous_page": null,
"next_page": 2,
"current_page": 1,
"per_page": 1,
"params": {
"limit": "1",
"client_ids": "1001",
"is_open": "true"
}
},
"entities": [
{
"class": [
"object",
"Request"
],
"rel": "/rels/request",
"href": "/app/requests/745109",
"properties": {
"id": 745109,
"name": "Sidewalk/Curb Repair - 628128",
"description": "651032 STrevino - We live on a corner lot. The sidewalks have become increasingly uneven over time, causing standing water at multiple places on the sidewalks. This also often creates standing mud on the sidewalk particularly after rain.\r\n\r\nCould you please request that they be leveled back to be smooth and even and allow for proper drainage?\r\n\r\nThank Very Much,\r\nAllan Meyer\r\n281-380-7012",
"created_at": "2015-02-24T02:21:41.000Z",
"updated_at": "2016-05-06T14:14:53.684Z",
"creator_id": 1110277,
"permissions": "This is visible to Sugar Land",
"comments_count": 12,
"is_current_user_commenter": false,
"follows_count": 1,
"is_current_user_following": false,
"flags_count": 0,
"is_current_user_flagger": false,
"tags_count": 0,
"average_rating": 0,
"ratings_count": null,
"object_fields": [
{
"id": 7096,
"name": "Subdivision (if applicable)",
"description": "",
"created_at": "2015-08-20T01:26:43.441Z",
"updated_at": "2015-08-20T01:26:43.441Z",
"creator_id": null,
"permissions": "This is visible to Everyone",
"display_id": 7096,
"foreign_ids": [],
"klass": "RequestType",
"data_type": "STRING",
"is_allow_null": false,
"render_guide": "TEXT",
"default_value": null,
"default_permissions": {
"read": [
707318
],
"write": [
707318
]
},
"object_field_options": []
},
{
"id": 7097,
"name": "Your Street Number and Street Name (if different location)",
"description": "",
"created_at": "2015-08-20T01:26:43.466Z",
"updated_at": "2015-08-20T01:26:43.466Z",
"creator_id": null,
"permissions": "This is visible to Everyone",
"display_id": 7097,
"foreign_ids": [],
"klass": "RequestType",
"data_type": "STRING",
"is_allow_null": true,
"render_guide": "TEXT",
"default_value": null,
"default_permissions": {
"read": [
707318
],
"write": [
707318
]
},
"object_field_options": []
},
{
"id": 7095,
"name": "Your Contact Number",
"description": "",
"created_at": "2015-08-20T01:26:43.420Z",
"updated_at": "2015-08-20T01:26:43.420Z",
"creator_id": null,
"permissions": "This is visible to Everyone",
"display_id": 7095,
"foreign_ids": [],
"klass": "RequestType",
"data_type": "STRING",
"is_allow_null": false,
"render_guide": "TEXT",
"default_value": null,
"default_permissions": {
"read": [
707318
],
"write": [
707318
]
},
"object_field_options": []
},
{
"id": 7094,
"name": "Your Name",
"description": "",
"created_at": "2015-08-20T01:26:43.395Z",
"updated_at": "2015-08-20T01:26:43.395Z",
"creator_id": null,
"permissions": "This is visible to Everyone",
"display_id": 7094,
"foreign_ids": [],
"klass": "RequestType",
"data_type": "STRING",
"is_allow_null": false,
"render_guide": "TEXT",
"default_value": null,
"default_permissions": {
"read": [
707318
],
"write": [
707318
]
},
"object_field_options": []
}
],
"object_field_instances": [
{
"id": 702607,
"name": null,
"description": null,
"created_at": "2015-02-24T13:12:15.000Z",
"updated_at": "2015-08-20T04:14:39.720Z",
"permissions": "This is visible to Sugar Land",
"value": "Magnolia Plantation",
"object_field_id": 7096
},
{
"id": 702606,
"name": null,
"description": null,
"created_at": "2015-02-24T13:12:15.000Z",
"updated_at": "2015-08-20T04:14:39.702Z",
"permissions": "This is visible to Sugar Land",
"value": "2811 Grassy Knoll Ct.",
"object_field_id": 7097
},
{
"id": 702605,
"name": null,
"description": null,
"created_at": "2015-02-24T13:12:15.000Z",
"updated_at": "2015-08-20T04:14:39.682Z",
"permissions": "This is visible to Sugar Land",
"value": "281-380-7012",
"object_field_id": 7095
},
{
"id": 702604,
"name": null,
"description": null,
"created_at": "2015-02-24T13:12:15.000Z",
"updated_at": "2015-08-20T04:14:39.664Z",
"permissions": "This is visible to Sugar Land",
"value": "Allan Meyer",
"object_field_id": 7094
}
],
"display_id": 745109,
"foreign_ids": [],
"status": "IN_PROGRESS",
"priority": "MEDIUM",
"request_type_id": 29119,
"geo_location_id": 686866,
"workflow_node_id": 890541,
"workflow_graph_id": 706096,
"completed_at": "2015-02-25T16:13:17.000Z",
"due_at": "2016-05-10T05:00:00.000Z",
"due_status": "OPEN",
"client_id": 1001,
"display_foreign_id": false,
"api_source_id": 15,
"is_duplicate": false,
"is_self_closure_allowed": true,
"has_duplicates": false,
"use_permission_matrix": true,
"request_type_foreign_api_ids": [],
"primary_attachment_id": null,
"attachments_count": 0,
"primary_attachment": null,
"contact_info": {
"name": "Allan Meyer",
"full_name": "Allan Meyer",
"first_name": "Allan",
"last_name": "Meyer",
"username": "allanrmeyer",
"phone": "",
"email": "allanrmeyer#gmail.com",
"user_id": 1110277
},
"geo_location": {
"id": 686866,
"name": "2811 Grassy Knoll Court, Sugar Land, TX 77478, USA",
"description": null,
"created_at": "2015-08-20T04:06:13.717Z",
"updated_at": "2015-08-20T04:06:13.717Z",
"creator_id": null,
"permissions": "This is visible to Everyone",
"geo_data_id": 738892,
"postal_address_id": 682944,
"accuracy_m": null,
"latitude": 29.585971,
"longitude": -95.587433,
"geo_location": {},
"postal_address": {
"id": 682944,
"name": "2811 Grassy Knoll Court, Sugar Land, TX 77478, USA",
"description": "2811 Grassy Knoll Court, Sugar Land, TX 77478, USA",
"created_at": "2015-08-20T04:06:13.706Z",
"updated_at": "2015-08-20T04:06:13.706Z",
"permissions": "This is visible to Everyone",
"source": null,
"street_number": "2811",
"street_number_unit": null,
"street_name": "Grassy Knoll Court",
"postal_code": "77478",
"region_id": 17622,
"geo_data_id": null,
"intersection": null,
"formatted_address": "2811 Grassy Knoll Court"
}
},
"request_type_name": "Sidewalk/Curb Repair",
"creator_display_name": "Allan Meyer",
"api_source_name": "Iframe"
},
"actions": []
}
],
"actions": [],
"links": [
{
"rel": [
"self"
],
"href": "/app/requests?page=1&limit=1&sort_dir=asc&client_ids=1001&is_open=true"
},
{
"rel": [
"next"
],
"href": "/app/requests?page=2&limit=1&sort_dir=asc&client_ids=1001&is_open=true"
}
]
}
I've created the following RootObject class to map the JSON:
public class RootObject
{
public List<string> #class { get; set; }
public Properties2 properties { get; set; }
public List<Entity> entities { get; set; }
public List<object> actions { get; set; }
public List<Link> links { get; set; }
}
Previously the following code was working to deserialize the JSON into the RootObject:
var objResponse1 = JsonConvert.DeserializeObject<RootObject>(response2.Content);
However, my code is now throwing a JSON.net exception:
An unhandled exception of type
'Newtonsoft.Json.JsonSerializationException' occurred in
Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[ProcessOpenRequests.Program+RootObject]'
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.
Now, I have tried the following to deserialize the JSON string based on other StackOverflow posts in regards to this error but the error has persisted:
var test = JsonConvert.DeserializeObject<List<RootObject>>(response2.Content);
Any help would be greatly appreciated. Thanks!
*Updated
Here is the Entity class:
public class Entity
{
public List<string> #class { get; set; }
public string rel { get; set; }
public Properties2 properties { get; set; }
public Actions actions { get; set; }
}
And here is the Properties2 class:
public class Properties2
{
public int? id { get; set; }
public string name { get; set; }
public string description { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public int? creator_id { get; set; }
public string permissions { get; set; }
public int? comments_count { get; set; }
public bool is_current_user_commenter { get; set; }
public int? follows_count { get; set; }
public bool is_current_user_following { get; set; }
public int? flags_count { get; set; }
public bool is_current_user_flagger { get; set; }
public int? tags_count { get; set; }
public decimal average_rating { get; set; }
public object ratings_count { get; set; }
public List<ObjectField> object_fields { get; set; }
public List<ObjectFieldInstance> object_field_instances { get; set; }
public int? display_id { get; set; }
public List<object> foreign_ids { get; set; }
public string status { get; set; }
public string priority { get; set; }
public int? request_type_id { get; set; }
public int? geo_location_id { get; set; }
public int? workflow_node_id { get; set; }
public int? workflow_graph_id { get; set; }
public object completed_at { get; set; }
public string due_at { get; set; }
public string due_status { get; set; }
public int? client_id { get; set; }
public bool display_foreign_id { get; set; }
public int? api_source_id { get; set; }
public bool is_duplicate { get; set; }
public bool is_self_closure_allowed { get; set; }
public bool has_duplicates { get; set; }
public bool use_permission_matrix { get; set; }
public List<object> request_type_foreign_api_ids { get; set; }
public object primary_attachment_id { get; set; }
public int? attachments_count { get; set; }
public object primary_attachment { get; set; }
public ContactInfo contact_info { get; set; }
public GeoLocation geo_location { get; set; }
public string request_type_name { get; set; }
public string creator_display_name { get; set; }
public string api_source_name { get; set; }
}
You are trying to deserialize your JSON into a List<RootObject>. That requires your JSON to be an array, but your JSON is not an array, JSON arrays begin and end with [ and ].
Try desalinizing to a RootObject instead.
var test = JsonConvert.DeserializeObject<RootObject>(response2.Content);
So, here's what happened, the API I was receiving the JSON data from changed up the RootObject and where I was previously referencing Properties2, I needed to change that to reference Properites. I also had to change a bunch of integers to now receive null data. My original code to deserialize the RootObject (and Bruno Garcia's answer) is valid once again.
I have a ASP MVC project that is accessing an API to get bank holiday dates: https://www.gov.uk/bank-holidays.json
When I parse the JSON however I am getting problems when I try to get down to the level of the 'events'. Currently I have:
var json = new WebClient().DownloadString("https://www.gov.uk/bank-holidays.json");
JavaScriptSerializer serializer = new JavaScriptSerializer();
var test = serializer.Deserialize<Dictionary<string, Dictionary<string, object>>>(json);
I can't seem to be able to cast the final object in this deserializer to anything meaningful. I have tried a variety of objects, lists, arrays etc but nothing seem to work. I only ever seem to be able to cast it to object.
Ideally I'd like the JSON to be parsed to a meaningful object such as:
public class BankHoliday
{
public DateTime Date { get; set; }
public string Title { get; set; }
public Country CountryCode { get; set; }
public string Notes { get; set; }
public bool Bunting { get; set; }
}
public enum Country
{
EnglandWales,
Scotland,
NorthernIreland
}
I thought this would be fairly simple but I have tried everything. I'm sure it's something simple that I am missing.
Thanks
Don't use JavaScriptSerializer better choice is JSON.NET
On site json2csharp.com you can generate classes from JSON:
public class Event
{
public string title { get; set; }
public string date { get; set; }
public string notes { get; set; }
public bool bunting { get; set; }
}
public class EnglandAndWales
{
public string division { get; set; }
public List<Event> events { get; set; }
}
public class Scotland
{
public string division { get; set; }
public List<Event> events { get; set; }
}
public class NorthernIreland
{
public string division { get; set; }
public List<Event> events { get; set; }
}
public class RootObject
{
[JsonProperty(PropertyName = "england-and-wales")]
public EnglandAndWales EnglandAndWales { get; set; }
public Scotland scotland { get; set; }
[JsonProperty(PropertyName = "northern-ireland")]
public NorthernIreland NorthernIreland { get; set; }
}
And then deserialise it with this way:
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(output);
EDIT
Added properties in RootObject to handele bad names.
Tested on simplified JSON:
{
"england-and-wales": {
"division": "england-and-wales",
"events": [{
"title": "New Year’s Day",
"date": "2012-01-02",
"notes": "Substitute day",
"bunting": true
},
{
"title": "Good Friday",
"date": "2012-04-06",
"notes": "",
"bunting": false
},
{
"title": "Boxing Day",
"date": "2017-12-26",
"notes": "",
"bunting": true
}]
},
"scotland": {
"division": "scotland",
"events": [{
"title": "2nd January",
"date": "2012-01-02",
"notes": "",
"bunting": true
},
{
"title": "New Year’s Day",
"date": "2012-01-03",
"notes": "Substitute day",
"bunting": true
},
{
"title": "Boxing Day",
"date": "2017-12-26",
"notes": "",
"bunting": true
}]
},
"northern-ireland": {
"division": "northern-ireland",
"events": [{
"title": "New Year’s Day",
"date": "2012-01-02",
"notes": "Substitute day",
"bunting": true
},
{
"title": "St Patrick’s Day",
"date": "2012-03-19",
"notes": "Substitute day",
"bunting": true
},
{
"title": "Boxing Day",
"date": "2017-12-26",
"notes": "",
"bunting": true
}]
}
}
I would greatly encourage you to use json.net lirary
I think you key problème here is that you need to use your type (BankHoliday) in the type definition:
Dictionary<string, <Dictionary<string, BankHoliday>>
Why not just use dynamic?
public IHttpActionResult BankHolidays()
{
var rawJson = string.Empty;
using (var webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8; // Expected Content-Type response is "application/json; charset=utf-8"
rawJson = webClient.DownloadString("https://www.gov.uk/bank-holidays.json");
}
dynamic json = JsonConvert.DeserializeObject<dynamic>(rawJson);
return Ok(json);
}
It gives me error when deserializing this JSON File
{
"checkOut": "10:30",
"stars": 4,
"locationId": 953,
"propertyType": 6,
"checkIn": "15:00",
"trustyou": {
"languageSplit": [
{
"tripTypeSplit": [
{
"type": "family",
"percentage": 85
},
{
"type": "couple",
"percentage": 15
}
],
"name": "de",
"percentage": 100
}
],
"location": [
],
"reviewsCount": 83,
"popularity": 0,
"tripTypeSplit": [
{
"type": "family",
"percentage": 86
},
{
"type": "couple",
"percentage": 14
}
],
"sentimentScoreList": [
{
"categoryId": "14",
"ratio": "Good",
"shortText": "Great location",
"name": "Location",
"subcategories": [
],
"highlights": [
{
"text": "Beautiful location",
"confidence": 100
}
],
"reviewCount": 14,
"score": 100
},
{
"categoryId": "111",
"ratio": "Good",
"shortText": "Rather comfortable",
"name": "Comfort",
"subcategories": [
],
"highlights": [
],
"reviewCount": 5,
"score": 100
},
I have the following classes for this JSON
public class Root
{
[JsonProperty("checkIn")]
public string CheckIn { get; set; }
[JsonProperty("distance")]
public double Distance { get; set; }
[JsonProperty("hidden")]
public bool Hidden { get; set; }
[JsonProperty("trustyou")]
public Trustyou Trustyou { get; set; }
[JsonProperty("amenitiesV2")]
public AmenitiesV2 AmenitiesV2 { get; set; }
[JsonProperty("hasAirbnb")]
public bool HasAirbnb { get; set; }
[JsonProperty("checkOut")]
public string CheckOut { get; set; }
[JsonProperty("popularity")]
public int Popularity { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cntRooms")]
public int CntRooms { get; set; }
What seems to be the problem? i'm deserializing this using
string resp2 = await client.GetStringAsync("");
var hotelDetails = JsonConvert.DeserializeObject<IDictionary<string, HotelsDescriptionAPI.Root>>(resp2, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
foreach (var hoteldesc in hotelDetails)
{
MessageBox.Show(hoteldesc.Value.Id);
}
and the exact error is
"Error converting value 24545 to type and Error converting value "10:30" to type 'HotelsDescriptionAPI.Root'. Path 'checkOut', line 1, position 19."
Im trying to get the value of "Id", What could be the problem with my code?
Your deserialization code should be:
var hotelDetails = JsonConvert.DeserializeObject<HotelsDescriptionAPI.Root>(resp2,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
You're trying to deserialize it into a dictionary of string,Root, when the object itself is simply Root.
It does not seem to apply to your scenario, but note that when you do have JSON that is an array (root level children are array items, not properties), you may have to change the root object to subclass a compatible type.
For example:
public class RootObject : List<ChildObject>
{
}
public class ChildObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
For people that this does not help, and that are not using Entity Framework and or writing the domain classes by hand - make sure all your class properties match what is coming out of your data source in the same exact field order.