Related
I hope someone can help me out here, because I'm pretty stuck ;)
I do not understand the error I'm getting:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'OdosTest.OdosRecord' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Isn't my json respone (see in the bottom) okay?
I'm trying to deserialize my IRestResponse to a object, but with no luck. The classes should be finde, or where am I wrong?
Here is my code:
using System;
using RestSharp;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace OdosTest
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://triscan.odosolutions.com/api/v1/streams");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic HIDDEN");
IRestResponse response = client.Execute(request);
var odosRecord = JsonConvert.DeserializeObject<OdosRecord>(response.Content);
//Console.WriteLine(response.Content);
}
}
public class OdosRecord
{
public int version { get; set; }
public string id { get; set; }
public int loggerImei { get; set; }
public string vin { get; set; }
public DateTime startTime { get; set; }
public Signal[] signals { get; set; }
}
public class Signal
{
public string source { get; set; }
public string name { get; set; }
public string displayName { get; set; }
public string number { get; set; }
public string unit { get; set; }
public bool isNumericComplement { get; set; }
public Value[] values { get; set; }
}
public class Value
{
public DateTime timestamp { get; set; }
public string value { get; set; }
}
}
Here is the response I get:
[
{
"version": 1,
"id": "0414bafa-39fe-4924-a1e3-f2180161f058",
"loggerImei": 1000606,
"vin": "WF0VXXGCEVFY08396",
"startTime": "2020-07-03T12:59:04.000345Z",
"signals": [
{
"source": "OBD",
"name": "01_42_CMV",
"displayName": "CMV",
"number": "0142",
"unit": "V",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "13.78"
}
]
},
{
"source": "OBD",
"name": "DETECTED_PROTOCOL",
"displayName": "DETECTED_PROTOCOL",
"number": "N/A",
"unit": "",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "CAN"
}
]
},
{
"source": "OBD",
"name": "01_31_TravelledDistSinceCodeCleared",
"displayName": "TravelledDistSinceCodeCleared",
"number": "0131",
"unit": "km",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "53749"
}
]
}
]
}
]
Your json contains a List<OdosRecord>, so this should solve the issue:
var odosRecord = JsonConvert.DeserializeObject<List<OdosRecord>>(response.Content);
otherwise you cloud change your json to this (if you are able to change the contract):
{
"version": 1,
"id": "0414bafa-39fe-4924-a1e3-f2180161f058",
"loggerImei": 1000606,
"vin": "WF0VXXGCEVFY08396",
"startTime": "2020-07-03T12:59:04.000345Z",
"signals": [
{
"source": "OBD",
"name": "01_42_CMV",
"displayName": "CMV",
"number": "0142",
"unit": "V",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "13.78"
}
]
},
{
"source": "OBD",
"name": "DETECTED_PROTOCOL",
"displayName": "DETECTED_PROTOCOL",
"number": "N/A",
"unit": "",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "CAN"
}
]
},
{
"source": "OBD",
"name": "01_31_TravelledDistSinceCodeCleared",
"displayName": "TravelledDistSinceCodeCleared",
"number": "0131",
"unit": "km",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "53749"
}
]
}
]
}
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.
Im trying to deserialize this json, originally the Airlines property is a IList but this doesn't work because the values are changing, so i used Dictionary i can get the key just fine but the values are empty.
This is the Sample JSON i'm trying to deserialize
"airlines": {
"MH": {
"lowcost": true,
"name": "Jetstar Asia",
"alliance_name": null,
"id": 300,
"rates": "18",
"average_rate": "3.12"
},
"PR": {
"lowcost": true,
"name": "Tigerair",
"alliance_name": null,
"id": 800,
"rates": "26",
"average_rate": "3.41"
},
"CZ": {
"lowcost": false,
"name": "Singapore Airlines",
"alliance_name": "Star Alliance",
"id": 449,
"rates": "620",
"average_rate": "4.18"
},
"SQ": {
"lowcost": true,
"name": "AirAsia Zest",
"alliance_name": null,
"id": 839,
"rates": "104",
"average_rate": "2.56"
},
"GA": {
"lowcost": true,
"name": "CEBU Pacific Air",
"alliance_name": null,
"id": 169,
"rates": "72",
"average_rate": "3.44"
},
This is the properties
[JsonProperty("airlines")]
public Dictionary<string, Airlines> Airlines { get; set; }
public class Airlines
{
[JsonProperty("AirlineDetails")]
public ICollection<AirlineDetails> AirlineDetails { get; set; }
}
public class AirlineDetails
{
[JsonProperty("average_rate")]
public string AverageRate { get; set; }
[JsonProperty("alliance_name")]
public string AllianceName { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("lowcost")]
public bool Lowcost { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("rates")]
public string Rates { get; set; }
}
Picture below shows there is a count which is 5 exactly as the JSON object count above, but the values are empty, i also want to get the values which is the name of airline.
Empty Value:
Airlines class is not necessary. Declare your property as Dictionary<string, AirlineDetails>:
public Dictionary<string, AirlineDetails> Airlines { get; set; }
I am trying to de-serialize this json string:
{"PatientData":[
{
"device": {
"serial": "M01106798",
"manufacturer": "Nipro",
"model": "TrueResult",
"first_value_at": "2010-07-17T22:39:00",
"last_value_at": "2010-09-30T11:18:00",
"supports_glucose": "no",
"supports_cgm": "no",
"supports_insulin": "no",
"supports_carb": "no"
},
"data": []
},
{
"device": {
"serial": "59-50889-10",
"manufacturer": "Animas",
"model": "IR1200",
"first_value_at": "2014-02-07T11:46:00",
"last_value_at": "2014-03-27T10:38:00",
"supports_glucose": "no",
"supports_cgm": "no",
"supports_insulin": "no",
"supports_carb": "no"
},
"data": [
{
"type": "insulin_bolus",
"created_at": "2014-02-07T23:42:00",
"unit": "U",
"total_value": 0.9,
"spike_value": 0.9,
"flags": [
{
"flag": 1008,
"description": "Bolus inactive"
}
]
},
{
"type": "insulin_basal",
"created_at": "2014-02-08T00:01:00",
"value": 0.175,
"unit": "U/h",
"flags": []
},
{
"type": "insulin_basal",
"created_at": "2014-02-08T05:01:00",
"value": 0.225,
"unit": "U/h",
"flags": []
},
{
"type": "insulin_bolus",
"created_at": "2014-02-08T07:42:00",
"unit": "U",
"total_value": 2.6,
"duration": 1800,
"flags": []
},
{
"type": "insulin_bolus",
"created_at": "2014-02-08T09:38:00",
"unit": "U",
"total_value": 0.3,
"spike_value": 0.3,
"flags": [
{
"flag": 1008,
"description": "Bolus inactive"
}
]
},
{
"type": "glucose",
"created_at": "2014-03-27T12:55:18",
"value": 33.167,
"unit": "mmol/l",
"flags": []
}
]
}
]}
by using classes generated from json2csharp like this
public class ObjPatientData
{
public class Device
{
public string serial { get; set; }
public string manufacturer { get; set; }
public string model { get; set; }
public string first_value_at { get; set; }
public string last_value_at { get; set; }
public string supports_glucose { get; set; }
public string supports_cgm { get; set; }
public string supports_insulin { get; set; }
public string supports_carb { get; set; }
}
public class PatientData
{
public Device device { get; set; }
public List<object> data { get; set; }
}
public class RootObject
{
public List<PatientData> PatientData { get; set; }
}
}
and calling it like this:
LPatientData = new List<ObjPatientData.RootObject>();
LPatientData = JsonConvert.DeserializeObject<List<ObjPatientData.RootObject>>(Json);
but I get a list of empty objects; any help will be appreciated.
Thanks!
please note that
Based on the above classes, I solved the issue by returning a list of "PatientData" objects rather than a list of "RootObjects" and using a Jarray.Parse(Json) in this way:
ObjPatientData.RootObject Root = new ObjPatientData.RootObject();
var jArray = JArray.Parse(Json);
Root.PatientData = jArray.ToObject<List<ObjPatientData.PatientData>>();
I think following the code will work.
string json = "{\"PatientData\":[{\"device\": {\"serial\": \"M01106798\",\"manufacturer\": \"Nipro\",\"model\": \"TrueResult\",\"first_value_at\": \"2010-07-17T22:39:00\",\"last_value_at\": \"2010-09-30T11:18:00\",\"supports_glucose\": \"no\",\"supports_cgm\": \"no\",\"supports_insulin\": \"no\",\"supports_carb\": \"no\"},\"data\": []},{\"device\": {\"serial\": \"59-50889-10\",\"manufacturer\": \"Animas\",\"model\": \"IR1200\",\"first_value_at\": \"2014-02-07T11:46:00\",\"last_value_at\": \"2014-03-27T10:38:00\",\"supports_glucose\": \"no\",\"supports_cgm\": \"no\",\"supports_insulin\": \"no\",\"supports_carb\": \"no\"},\"data\": [ {\"type\": \"insulin_bolus\",\"created_at\": \"2014-02-07T23:42:00\",\"unit\": \"U\",\"total_value\": 0.9,\"spike_value\": 0.9,\"flags\": [{\"flag\": 1008,\"description\": \"Bolus inactive\"}]},{\"type\": \"insulin_basal\",\"created_at\": \"2014-02-08T00:01:00\",\"value\": 0.175,\"unit\": \"U/h\",\"flags\": []},{\"type\": \"insulin_basal\",\"created_at\": \"2014-02-08T05:01:00\",\"value\": 0.225,\"unit\": \"U/h\",\"flags\": []},{\"type\": \"insulin_bolus\",\"created_at\": \"2014-02-08T07:42:00\",\"unit\": \"U\",\"total_value\": 2.6,\"duration\": 1800,\"flags\": []},{\"type\": \"insulin_bolus\",\"created_at\": \"2014-02-08T09:38:00\",\"unit\": \"U\",\"total_value\": 0.3,\"spike_value\": 0.3,\"flags\": [{\"flag\": 1008,\"description\": \"Bolus inactive\"}]}, {\"type\": \"glucose\",\"created_at\": \"2014-03-27T12:55:18\",\"value\": 33.167,\"unit\": \"mmol/l\",\"flags\": []}]}]}";
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
RootObject rootObject = javaScriptSerializer.Deserialize<RootObject>(json);
I am not able to get my head around extracting the work_history, affiliations and current_loc of the facebook user from the JSON string that is generated after i run my fql query
I have made this class :
public class Data
{
public CurrentLocation current_location { get; set; }
public WorkHistory[] work_history { get; set; }
public EducationHistory[] education_history { get; set; }
}
public class EducationHistory
{
public string name { get; set; }
public int? year { get; set; }
public string school_type { get; set; }
}
public class WorkHistory
{
public string company_name { get; set; }
public Location location { get; set; }
}
public class CurrentLocation
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
}
public class Location
{
public string city { get; set; }
public string state { get; set; }
}
The format of my JSON string is :
{"current_location":{"city":"Delhi","state":"Delhi","country":"India","zip":"","id":102161913158207,"name":"Delhi, India"}
,"education_history":[{"name":"I E T , Alwar (Raj.)","year":2007,"concentrations":[],"school_type":"College"},{"name":"Institute of Engineering and Technology, Alwar","concentrations":[],"school_type":"College"}],
"work_history": [{"location":{"city":"","state":""},"company_name":"Defence Research & Development Organisation (DRDO)","description":"","start_date":"0000-00","end_date":"0000-00"}]}
How do i extract this Data i get a null when i use this code :
Data soap = JsonConvert.DeserializeObject<Data>(ser);
Edit : I did change the code according to what an answer suggested i still get no values
Edit 2: the solution that is provided would have worked if i had only one user however i have several users having these details how do i get this data? There are several like these values given below for different users
{
"data": [
{
"uid": 54456565,
"name": "dgfg Barma",
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash2/275277_513046358_147089990_q.jpg",
"affiliations": [
{
"nid": 33605704,
"name": "Our Lady Queen of the Missions School",
"type": "high school"
}
],
"birthday_date": null,
"sex": "female",
"relationship_status": null,
"current_location": {
"city": "Delhi",
"state": "Delhi",
"country": "India",
"zip": "",
"id": 102161913158207,
"name": "Delhi, India"
},
"education_history": [
{
"name": "Amity University",
"concentrations": [],
"school_type": "College"
},
{
"name": "Amity School of Engineering & Technology",
"concentrations": [],
"school_type": "College"
}
],
"work_history": []
},
{
"uid": 520310824,
"name": "Mamta Meena",
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/370835_520310824_553662476_q.jpg",
"affiliations": [],
"birthday_date": "12/03/1986",
"sex": "female",
"relationship_status": "Married",
"current_location": {
"city": "Delhi",
"state": "Delhi",
"country": "India",
"zip": "",
"id": 102161913158207,
"name": "Delhi, India"
},
"education_history": [
{
"name": "I E T , Alwar (Raj.)",
"year": 2007,
"concentrations": [],
"school_type": "College"
},
{
"name": "Institute of Engineering and Technology, Alwar",
"concentrations": [],
"school_type": "College"
}
],
"work_history": [
{
"location": {
"city": "",
"state": ""
},
"company_name": "Defence Research & Development Organisation (DRDO)",
"description": "",
"start_date": "0000-00",
"end_date": "0000-00"
}
]
},
{
"uid": 6565767,
"name": "gfgfg Agarwal",
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash2/372433_529863326_1656605196_q.jpg",
"affiliations": [
{
"nid": 16827518,
"name": "Amity University",
"type": "college"
}
],
"birthday_date": "07/18",
"sex": "female",
"relationship_status": null,
"current_location": {
"city": "Delhi",
"state": "Delhi",
"country": "India",
"zip": "",
"id": 102161913158207,
"name": "Delhi, India"
},
"education_history": [
{
"name": "Amity University, Noida",
"year": 2012,
"concentrations": [],
"school_type": "College"
},
{
"name": "Amity University",
"concentrations": [],
"school_type": "Grad School"
}
],
"work_history": []
},
{
"uid": 542580357,
"name": "bnnm Gupta",
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/372576_542580357_1330958366_q.jpg",
"affiliations": [],
"birthday_date": "04/30",
"sex": "female",
"relationship_status": "Single",
"current_location": {
"city": "New Delhi",
"state": "Delhi",
"country": "India",
"zip": "",
"id": 106517799384578,
"name": "New Delhi, India"
},
"education_history": [
{
"name": "Amity University",
"concentrations": [],
"school_type": "College"
},
{
"name": "Amity University, Noida",
"concentrations": [],
"school_type": "College"
}
],
"work_history": [
{
"location": {
"city": "",
"state": ""
},
"company_name": "Oracle India Pvt Ltd",
"position": "Intern",
"description": "",
"start_date": "2011-05"
}
]
},
{
"uid": 544204117,
"name": "pos Gupta",
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/275346_544204117_594313449_q.jpg",
"affiliations": [
{
"nid": 16827518,
"name": "Amity University",
"type": "college"
}
],
"birthday_date": "05/17/1990",
"sex": "female",
"relationship_status": "Single",
"current_location": {
"city": "Noida",
"state": "Uttar Pradesh",
"country": "India",
"zip": "",
"id": 130646063637019,
"name": "Noida, India"
},
"education_history": [
{
"name": "Amity University, Noida",
"year": 2012,
"concentrations": [],
"school_type": "College"
},
{
"name": "Amity University",
"concentrations": [],
"school_type": "Grad School"
}
],
"work_history": []
},
{
"uid": 4567786,
"name": "orr Makhijani",
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/372443_555253796_244086438_q.jpg",
"affiliations": [
{
"nid": 16827518,
"name": "Amity University",
"type": "college"
}
],
"birthday_date": null,
"sex": "female",
"relationship_status": null,
"current_location": null,
"education_history": [
{
"name": "Amity University",
"concentrations": [],
"school_type": "College"
}
],
"work_history": []
},
{
"uid": 556773604,
"name": "Nazima Khalid",
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash2/372542_556773604_1472126324_q.jpg",
"affiliations": [],
"birthday_date": "03/22",
"sex": "female",
"relationship_status": "Married",
"current_location": {
"city": "Toronto",
"state": "Ontario",
"country": "Canada",
"zip": "",
"id": 110941395597405,
"name": "Toronto, Ontario"
},
"education_history": [
{
"name": "AMU",
"concentrations": [],
"school_type": "College"
}
],
"work_history": [
{
"location": {
"city": "Oakville",
"state": "Ontario"
},
"company_name": "SNC-Lavalin Inc.",
"position": "Contracts",
"description": "",
"start_date": "0000-00"
}
]
}
]
}
Please help
Instead of declaring a lot of tiny classes I would go dynamic way. Here is the code for dynamic json object. And the usage would be something like this:
dynamic obj = JsonUtils.JsonObject.GetDynamicJsonObject(jsonString);
Console.WriteLine("{0} , {1}", obj.current_location.city, obj.current_location.state);
Console.WriteLine("EDUCATION");
foreach (var eduHist in obj.education_history)
{
Console.WriteLine("{0} , {1}", eduHist.name, eduHist.year);
}
Console.WriteLine("WORK");
foreach (var workHist in obj.work_history)
{
Console.WriteLine("{0} {1}-{2}", workHist.company_name, workHist.start_date, workHist.end_date);
}
You need to use correct property names that match your JSON structure:
using System;
using Newtonsoft.Json;
public class Data
{
public CurrentLocation current_location { get; set; }
public WorkHistory[] work_history { get; set; }
public EducationHistory[] education_history { get; set; }
}
public class EducationHistory
{
public string name { get; set; }
public int? year { get; set; }
public string school_type { get; set; }
}
public class WorkHistory
{
public string company_name { get; set; }
public Location location { get; set; }
}
public class CurrentLocation
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
}
public class Location
{
public string city { get; set; }
public string state { get; set; }
}
class Program
{
static void Main()
{
var json =
#"
{
""current_location"": {
""city"": ""Delhi"",
""state"": ""Delhi"",
""country"": ""India"",
""zip"": """",
""id"": 102161913158207,
""name"": ""Delhi, India""
},
""education_history"": [
{
""name"": ""I E T , Alwar (Raj.)"",
""year"": 2007,
""concentrations"": [],
""school_type"": ""College""
},
{
""name"": ""Institute of Engineering and Technology, Alwar"",
""concentrations"": [],
""school_type"": ""College""
}
],
""work_history"": [
{
""location"": {
""city"": """",
""state"": """"
},
""company_name"": ""Defence Research & Development Organisation (DRDO)"",
""description"": """",
""start_date"": ""0000-00"",
""end_date"": ""0000-00""
}
]
}";
Data soap = JsonConvert.DeserializeObject<Data>(json);
Console.WriteLine(soap.current_location.city);
}
}
As far as the affiliations property is concerned, I don't see any relation to it with your JSON, so I simply removed it from the Data object and replaced it with the EducationHistory type.
UPDATE:
And to handle multiple nodes you could adapt your models:
public class Result
{
public Data[] data { get; set; }
}
public class Data
{
public CurrentLocation current_location { get; set; }
public WorkHistory[] work_history { get; set; }
public EducationHistory[] education_history { get; set; }
}
public class EducationHistory
{
public string name { get; set; }
public int? year { get; set; }
public string school_type { get; set; }
}
public class WorkHistory
{
public string company_name { get; set; }
public Location location { get; set; }
}
public class CurrentLocation
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
}
public class Location
{
public string city { get; set; }
public string state { get; set; }
}
and then:
Result soap = JsonConvert.DeserializeObject<Result>(json);
Console.WriteLine(soap.data[0].current_location.city);
Here's another example that's working for retrieving id, name, picture and friends. You must include reference to newtonsoft.json package.
[TestClass]
public class FbRequestParserTests
{
[TestMethod]
public void ParseFacebookResponse()
{
var response =
#"{
""id"": ""123123"",
""name"": ""My name"",
""picture"": {
""data"": {
""is_silhouette"": false,
""url"": ""https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/14572785_123""
}
},
""friends"": {
""data"": [
{
""name"": ""Friend 1"",
""id"": ""123""
},
{
""name"": ""Friend 2"",
""id"": ""234""
}
],
""paging"": {
""cursors"": {
""before"": ""QVFIUk1yRE9zTkhFdkc1TFV2SHVpaE1IYUJ4V2ljbUJSbjYxaGhnX05IcTNYWHp0ekNHZAnh6LThs"",
""after"": ""QVFIUjFFQW5kVmJiTmMxZAHN6cWNDdUl5VnVJVl91UG0yV2hMOVl5N21GTDVxQ2JVQ2hjQVlRYXBxNDNkWWI3YjZAkZAFBV""
}
},
""summary"": {
""total_count"": 456
}
}
}";
var result = JsonConvert.DeserializeObject<FbResponse>(response);
Assert.AreEqual(result.Id, 123123);
Assert.AreEqual(result.Name, "My Name");
}
}
public class FbResponse
{
public long Id { get; set; }
public string Name { get; set; }
public Picture Picture { get; set; }
public Friends Friends { get; set; }
}
public class Friends
{
public List<FriendsData> Data { get; set; }
public Paging Paging { get; set; }
public Summary Summary { get; set; }
}
public class Summary
{
public int Total_Count { get; set; }
}
public class Paging
{
public Cursors Cursors { get; set; }
}
public class Cursors
{
public string Before { get; set; }
public string After { get; set; }
}
public class FriendsData
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Picture
{
public PictureData Data { get; set; }
}
public class PictureData
{
public bool Is_Silhouette { get; set; }
public string Url { get; set; }
}