I am trying to deserialize the following JSON, but I really have no idea how to use JSON.net to do the work. I am using C# and JSON.Net library.
My JSON is as follows:
{
"found": 3,
"bounds": [
[
-43.54919,
172.62148
],
[
-43.54487,
172.63654
]
],
"features": [
{
"id": 15342454,
"centroid": {
"type": "POINT",
"coordinates": [
-43.54779,
172.62148
]
},
"bounds": [
[
-43.54779,
172.62148
],
[
-43.54779,
172.62148
]
],
"properties": {
"osm_element": "node",
"amenity": "toilets",
"synthesized_name": "Toilets",
"osm_id": "502884303"
},
"geometry": {
"type": "POINT",
"coordinates": [
-43.54779,
172.62148
]
},
"location": {
"county": "Canterbury",
"country": "New Zealand",
"road": "Sommerset Crescent",
"city": "Christchurch"
},
"type": "Feature"
},
{
"id": 19313858,
"centroid": {
"type": "POINT",
"coordinates": [
-43.54919,
172.63654
]
},
"bounds": [
[
-43.54919,
172.63654
],
[
-43.54919,
172.63654
]
],
"properties": {
"osm_element": "node",
"amenity": "toilets",
"synthesized_name": "Toilets",
"osm_id": "676225633"
},
"geometry": {
"type": "POINT",
"coordinates": [
-43.54919,
172.63654
]
},
"location": {
"county": "Canterbury",
"country": "New Zealand",
"road": "Colombo Street",
"city": "Christchurch"
},
"type": "Feature"
},
{
"id": 22536275,
"centroid": {
"type": "POINT",
"coordinates": [
-43.54487,
172.63632
]
},
"bounds": [
[
-43.54487,
172.63632
],
[
-43.54487,
172.63632
]
],
"properties": {
"osm_element": "node",
"amenity": "toilets",
"synthesized_name": "Toilets",
"osm_id": "864392689"
},
"geometry": {
"type": "POINT",
"coordinates": [
-43.54487,
172.63632
]
},
"location": {
"county": "Canterbury",
"country": "New Zealand",
"road": "Wordsworth Street",
"city": "Christchurch"
},
"type": "Feature"
}
],
"type": "FeatureCollection",
"crs": {
"type": "EPSG",
"properties": {
"code": 4326,
"coordinate_order": [
0,
1
]
}
}
}
You don't have to declare many tiny classes to deserialize. Just make use of dynamic.
Here is a working example
string jsonstr = #"{""found"": 3, ""bounds"": [[-43.54919, 172.62148], [-43.54487, 172.63654]], ""features"": [{""id"": 15342454,""centroid"": {""type"":""POINT"",""coordinates"":[-43.54779, 172.62148]},""bounds"": [[-43.54779, 172.62148], [-43.54779, 172.62148]],""properties"": {""osm_element"": ""node"", ""amenity"": ""toilets"", ""synthesized_name"": ""Toilets"", ""osm_id"": ""502884303""},""geometry"": {""type"":""POINT"",""coordinates"":[-43.54779, 172.62148]},""location"": {""county"": ""Canterbury"", ""country"": ""New Zealand"", ""road"": ""Sommerset Crescent"", ""city"": ""Christchurch""},""type"": ""Feature""},{""id"": 19313858,""centroid"": {""type"":""POINT"",""coordinates"":[-43.54919, 172.63654]},""bounds"": [[-43.54919, 172.63654], [-43.54919, 172.63654]],""properties"": {""osm_element"": ""node"", ""amenity"": ""toilets"", ""synthesized_name"": ""Toilets"", ""osm_id"": ""676225633""},""geometry"": {""type"":""POINT"",""coordinates"":[-43.54919, 172.63654]},""location"": {""county"": ""Canterbury"", ""country"": ""New Zealand"", ""road"": ""Colombo Street"", ""city"": ""Christchurch""},""type"": ""Feature""},{""id"": 22536275,""centroid"": {""type"":""POINT"",""coordinates"":[-43.54487, 172.63632]},""bounds"": [[-43.54487, 172.63632], [-43.54487, 172.63632]],""properties"": {""osm_element"": ""node"", ""amenity"": ""toilets"", ""synthesized_name"": ""Toilets"", ""osm_id"": ""864392689""},""geometry"": {""type"":""POINT"",""coordinates"":[-43.54487, 172.63632]},""location"": {""county"": ""Canterbury"", ""country"": ""New Zealand"", ""road"": ""Wordsworth Street"", ""city"": ""Christchurch""},""type"": ""Feature""}], ""type"": ""FeatureCollection"", ""crs"": {""type"": ""EPSG"", ""properties"": {""code"": 4326, ""coordinate_order"": [0, 1]}}}";
dynamic json = JsonConvert.DeserializeObject(jsonstr);
foreach (var feature in json.features)
{
Console.Write("{0},{1} - {2},{3} : ",
feature.bounds[0][0], feature.bounds[0][1],
feature.bounds[1][0], feature.bounds[1][1]);
Console.WriteLine("{0} {1} {2} {3}",
feature.location.country, feature.location.county, feature.location.city, feature.location.road);
}
Non-dynamic version
JObject json = (JObject)JsonConvert.DeserializeObject(jsonstr);
foreach (var feature in json["features"])
{
Console.Write("{0},{1} - {2},{3} : ",
feature["bounds"][0][0], feature["bounds"][0][1],
feature["bounds"][1][0], feature["bounds"][1][1]);
Console.WriteLine("{0} {1} {2} {3}",
feature["location"]["country"], feature["location"]["county"], feature["location"]["city"], feature["location"]["road"]);
}
public class Centroid
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class Properties
{
public string osm_element { get; set; }
public string amenity { get; set; }
public string synthesized_name { get; set; }
public string osm_id { get; set; }
}
public class Geometry
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class Location
{
public string county { get; set; }
public string country { get; set; }
public string road { get; set; }
public string city { get; set; }
}
public class Feature
{
public int id { get; set; }
public Centroid centroid { get; set; }
public List<List<double>> bounds { get; set; }
public Properties properties { get; set; }
public Geometry geometry { get; set; }
public Location location { get; set; }
public string type { get; set; }
}
public class Properties2
{
public int code { get; set; }
public List<int> coordinate_order { get; set; }
}
public class Crs
{
public string type { get; set; }
public Properties2 properties { get; set; }
}
public class RootObject
{
public int found { get; set; }
public List<List<double>> bounds { get; set; }
public List<Feature> features { get; set; }
public string type { get; set; }
public Crs crs { get; set; }
}
Here you go.
There is a tool for generating C# classes from json http://json2csharp.com/.
First create a class that fits the JSONed object.
Then, simply write JsonConvert.DeserializeObject<ClassName>(json)
Where ClassName is the name of your class and json is a string containing you JSON.
You have quite a complex data structure, so creating a class for it might be a bit complex.
You might want to maybe simplify it a little bit.
How I would tackle this....
First take your JSON and paste it into: http://jsonviewer.stack.hu/ - this gives you a view like:
Now, from the objects shown in that view create a class for each type of object - e.g:
public class MainWrapper
{
public int found {get;set;}
public List<Bound> bounds {get;set;}
public List<Feature> features {get;set;}
public Crs crs {get;set;
}
Finally you can now use some Newtonsoft to deserialize as: JsonConvert.DeserializeObject<MainWrapper>(text)
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 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
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.
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; }
}