I am trying to deserialize my web response json to an object, at the time object gettingnull after deserialization. This is my code:
JSON response:
{
"#odata.context": "https://outlook.office365.com/api/v1.0/$metadata#Me/CalendarView",
"value": [
{
"#odata.id": "https://outlook.office365.com/api/v1.0/Users('sathesh#newtechsolution.onmicrosoft.com')/Events('AAMkADQzMGVmNjZmLWY1YjAtNGFkYS1hODY0LTdiMWZlZjZjYmIwOABGAAAAAAAaluoeH9c2Qq33MvKTCqzgBwD1QTj3IO57QaWZ9MZF6weaAAAAAAENAAD1QTj3IO57QaWZ9MZF6weaAAAAAA0kAAA=')",
"#odata.etag": "W/\"9UE49yDue0GlmfTGResHmgAAAAANag==\"",
"Id": "AAMkADQzMGVmNjZmLWY1YjAtNGFkYS1hODY0LTdiMWZlZjZjYmIwOABGAAAAAAAaluoeH9c2Qq33MvKTCqzgBwD1QTj3IO57QaWZ9MZF6weaAAAAAAENAAD1QTj3IO57QaWZ9MZF6weaAAAAAA0kAAA=",
"ChangeKey": "9UE49yDue0GlmfTGResHmgAAAAANag==",
"Categories": [],
"DateTimeCreated": "2015-05-20T12:03:09.4043813Z",
"DateTimeLastModified": "2015-05-20T12:03:09.5606394Z",
"Subject": "Interview Sample",
"BodyPreview": "Interview For API discussion.",
"Body": {
"ContentType": "HTML",
"Content": "<html>\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n<style type=\"text/css\" style=\"display:none;\"><!-- P {margin-top:0;margin-bottom:0;} --></style>\r\n</head>\r\n<body dir=\"ltr\">\r\n<div id=\"divtagdefaultwrapper\" style=\"font-size:12pt;color:#000000;background-color:#FFFFFF;font-family:Calibri,Arial,Helvetica,sans-serif;\">\r\n<p>Interview For API discussion.<br>\r\n</p>\r\n</div>\r\n</body>\r\n</html>\r\n"
},
"Importance": "Normal",
"HasAttachments": false,
"Start": "2015-05-20T16:00:00Z",
"StartTimeZone": "Sri Lanka Standard Time",
"End": "2015-05-20T17:00:00Z",
"EndTimeZone": "Sri Lanka Standard Time",
"Reminder": 15,
"Location": {
"DisplayName": "Interview Sample Chennai MRC NAGAR",
"Address": { "Street": "", "City": "", "State": "", "CountryOrRegion": "", "PostalCode": "" },
"Coordinates": { "Accuracy": "NaN", "Altitude": "NaN", "AltitudeAccuracy": "NaN", "Latitude": "NaN", "Longitude": "NaN" }
},
"ResponseStatus": { "Response": "Organizer", "Time": "0001-01-01T00:00:00Z" },
"ShowAs": "Busy",
"IsAllDay": false,
"IsCancelled": false,
"IsOrganizer": true,
"ResponseRequested": true,
"Type": "SingleInstance",
"SeriesMasterId": null,
"Attendees": [
{
"EmailAddress": { "Address": "skumar#viswambara.com", "Name": "skumar#viswambara.com" },
"Status": { "Response": "None", "Time": "0001-01-01T00:00:00Z" },
"Type": "Required"
}
],
"Recurrence": null,
"Organizer": {
"EmailAddress": { "Address": "sathesh#newtechsolution.onmicrosoft.com", "Name": "sathesh kumar" }
},
"iCalUId": "040000008200E00074C5B7101A82E0080000000019D340F0F492D0010000000000000000100000005BA1B6261EECD34D991C5BE7D4A70547"
}
]
}
Class:
public class value
{
public string Id { get; set; }
public string ChangeKey { get; set; }
public List<object> Categories { get; set; }
public string DateTimeCreated { get; set; }
public string DateTimeLastModified { get; set; }
public string Subject { get; set; }
public string BodyPreview { get; set; }
public Body Body { get; set; }
public string Importance { get; set; }
public bool HasAttachments { get; set; }
public string Start { get; set; }
public string StartTimeZone { get; set; }
public string End { get; set; }
public string EndTimeZone { get; set; }
public int Reminder { get; set; }
public Location Location { get; set; }
public ResponseStatus ResponseStatus { get; set; }
public string ShowAs { get; set; }
public bool IsAllDay { get; set; }
public bool IsCancelled { get; set; }
public bool IsOrganizer { get; set; }
public bool ResponseRequested { get; set; }
public string Type { get; set; }
public object SeriesMasterId { get; set; }
public List<Attendee> Attendees { get; set; }
public object Recurrence { get; set; }
public Organizer Organizer { get; set; }
public string iCalUId { get; set; }
}
Deserialization:
JavaScriptSerializer json = new JavaScriptSerializer();
value condiiton = (value)json.Deserialize(responcedata, typeof(value));
Let's look at your JSON object. You actually have an anonymous JSON (let's call it response) object with two objects: string '#odata.context' and array 'value' of objects of value C# class type.
You have described value class but now you are trying do deserialize response object to value which is incorrect.
You need to describe the corresponding class and deserialize it.
public class Response
{
public value[] value { get; set; }
}
Then you can do it this way:
JavaScriptSerializer json = new JavaScriptSerializer();
Response response = (Response)json.Deserialize(responcedata, typeof(Response));
Related
I'm trying to create a custom type in C# that can handle rdap.org responses upon JSON deserialization (for my purposes I'll be using netwonsoft).
For example in making a GET request to: https://rdap.org/domain/stackoverflow.com
the following JSON string is returned:
{
"objectClassName": "domain",
"handle": "108907621_DOMAIN_COM-VRSN",
"ldhName": "STACKOVERFLOW.COM",
"links": [
{
"value": "https://rdap.verisign.com/com/v1/domain/STACKOVERFLOW.COM",
"rel": "self",
"href": "https://rdap.verisign.com/com/v1/domain/STACKOVERFLOW.COM",
"type": "application/rdap+json"
},
{
"value": "https://apis.cscglobal.com/dbs/rdap-api/v1/domain/STACKOVERFLOW.COM",
"rel": "related",
"href": "https://apis.cscglobal.com/dbs/rdap-api/v1/domain/STACKOVERFLOW.COM",
"type": "application/rdap+json"
}
],
"status": [
"client transfer prohibited"
],
"entities": [
{
"objectClassName": "entity",
"handle": "299",
"roles": [
"registrar"
],
"publicIds": [
{
"type": "IANA Registrar ID",
"identifier": "299"
}
],
"vcardArray": [
"vcard",
[
[
"version",
{},
"text",
"4.0"
],
[
"fn",
{},
"text",
"CSC Corporate Domains, Inc."
]
]
],
"entities": [
{
"objectClassName": "entity",
"roles": [
"abuse"
],
"vcardArray": [
"vcard",
[
[
"version",
{},
"text",
"4.0"
],
[
"fn",
{},
"text",
""
],
[
"tel",
{
"type": "voice"
},
"uri",
"tel:8887802723"
],
[
"email",
{},
"text",
"domainabuse#cscglobal.com"
]
]
]
}
]
}
],
"events": [
{
"eventAction": "registration",
"eventDate": "2003-12-26T19:18:07Z"
},
{
"eventAction": "expiration",
"eventDate": "2024-02-02T11:59:59Z"
},
{
"eventAction": "last changed",
"eventDate": "2022-08-17T04:32:10Z"
},
{
"eventAction": "last update of RDAP database",
"eventDate": "2023-01-29T11:05:33Z"
}
],
"secureDNS": {
"delegationSigned": false
},
"nameservers": [
{
"objectClassName": "nameserver",
"ldhName": "NS-1033.AWSDNS-01.ORG"
},
{
"objectClassName": "nameserver",
"ldhName": "NS-358.AWSDNS-44.COM"
},
{
"objectClassName": "nameserver",
"ldhName": "NS-CLOUD-E1.GOOGLEDOMAINS.COM"
},
{
"objectClassName": "nameserver",
"ldhName": "NS-CLOUD-E2.GOOGLEDOMAINS.COM"
}
],
"rdapConformance": [
"rdap_level_0",
"icann_rdap_technical_implementation_guide_0",
"icann_rdap_response_profile_0"
],
"notices": [
{
"title": "Terms of Use",
"description": [
"Service subject to Terms of Use."
],
"links": [
{
"href": "https://www.verisign.com/domain-names/registration-data-access-protocol/terms-service/index.xhtml",
"type": "text/html"
}
]
},
{
"title": "Status Codes",
"description": [
"For more information on domain status codes, please visit https://icann.org/epp"
],
"links": [
{
"href": "https://icann.org/epp",
"type": "text/html"
}
]
},
{
"title": "RDDS Inaccuracy Complaint Form",
"description": [
"URL of the ICANN RDDS Inaccuracy Complaint Form: https://icann.org/wicf"
],
"links": [
{
"href": "https://icann.org/wicf",
"type": "text/html"
}
]
}
]
}
According to json2csharp.com the following custom type will do this:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Entity
{
public string objectClassName { get; set; }
public List<string> roles { get; set; }
public List<Remark> remarks { get; set; }
public List<string> status { get; set; }
public string handle { get; set; }
public List<object> vcardArray { get; set; }
public List<Entity> entities { get; set; }
public List<PublicId> publicIds { get; set; }
public List<Event> events { get; set; }
public List<Link> links { get; set; }
}
public class Event
{
public string eventAction { get; set; }
public DateTime eventDate { get; set; }
public string eventActor { get; set; }
}
public class Link
{
public string rel { get; set; }
public string value { get; set; }
public string href { get; set; }
public string type { get; set; }
public string title { get; set; }
}
public class Nameserver
{
public string objectClassName { get; set; }
public string handle { get; set; }
public string ldhName { get; set; }
public List<string> status { get; set; }
public List<Event> events { get; set; }
public List<Link> links { get; set; }
}
public class Notice
{
public string title { get; set; }
public List<string> description { get; set; }
public List<Link> links { get; set; }
}
public class PublicId
{
public string identifier { get; set; }
public string type { get; set; }
}
public class Remark
{
public string title { get; set; }
public string type { get; set; }
public List<string> description { get; set; }
public List<Link> links { get; set; }
}
public class Root
{
public List<string> rdapConformance { get; set; }
public string objectClassName { get; set; }
public string handle { get; set; }
public string ldhName { get; set; }
public List<string> status { get; set; }
public List<Event> events { get; set; }
public SecureDNS secureDNS { get; set; }
public List<Entity> entities { get; set; }
public List<Nameserver> nameservers { get; set; }
public List<Notice> notices { get; set; }
public List<Link> links { get; set; }
}
public class SecureDNS
{
public bool delegationSigned { get; set; }
}
And indeed, it does correctly deserialize that json into the type. There is just one very small and subtle problem: The line in the source code public List<object> vcardArray { get; set; } uses a list of "object", making access to the vcardArray very difficult. I'm currently converting each object to a string and using regexes to access them, however this doesn't seem right and feels finicky.
Is there any way I could modify the Entity class without using an 'object' for the vcardArray? Perhaps additional classes could be used? Every attempt I've made so far fails upon deserialization.
you can create a VCard class and add JsonConstructor to Entity class
public class VCard
{
public string CardType { get; set; }
public string ContactType { get; set; }
public string ValType { get; set; }
public string Val { get; set; }
}
public class Entity
{
//another properties
public List<VCard> VCards { get; set; }
[JsonConstructor]
public Entity(JToken vcardArray)
{
VCards = vcardArray.OfType<JArray>()
.Select(i => i.Select(x => new VCard
{
CardType = x[0].ToString(),
ContactType = ((JObject)x[1]).Properties().Count() == 0 ? ""
: String.Join(",", ((JObject)x[1]).Properties()),
ValType = x[2].ToString(),
Val = x[3].ToString()
})
.ToList())
.First();
}
}
We are using Netweaver Gateway to get data from SAP.
I have a class which I use with JsonConvert.DeserializeObject<ODataObject> to get the JSON converted to my model. Which works fine.
But now we are working with HEADERS and ITEMS.
Can't get it converted to a (nested) model.
I got this JSON return from Netweaver Gateway:
{
"d": {
"__metadata": {
"id": "http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_hdrSet('1')",
"uri": "http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_hdrSet('1')",
"type": "ZLOTO_POC_SRV.WorkPermit_hdr"
},
"WpNr": "1",
"WoNr": "123456789",
"Desc1": "FLOP12",
"Desc2": "No ieda",
"Loc1": "",
"Loc2": "",
"Execution": "I",
"ExecDept": "'t smoorkot",
"ExecComp": "",
"SupExec": "Big boss",
"SupExecTel": "+32474895623",
"VpkInstr": "Mr unknown",
"VpkInstrTel": "+32474895624",
"WorkSup": "N/A",
"WorkSupTel": "+32474895625",
"Status": "",
"ValidFrom": null,
"ValidTo": null,
"CreateUser": "",
"ChangeUser": "",
"WorkPermit_hdr_itm_nav": {
"results": [{
"__metadata": {
"id": "http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_itmSet(WpNr='1',WoOper='00000001')",
"uri": "http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_itmSet(WpNr='1',WoOper='00000001')",
"type": "ZLOTO_POC_SRV.WorkPermit_itm"
},
"WpNr": "1",
"WoOper": "00000001",
"Desc": "First iitem desc",
"CreateUser": "TDPO",
"ChangeUser": "TDPO"
}, {
"__metadata": {
"id": "http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_itmSet(WpNr='1',WoOper='00000002')",
"uri": "http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_itmSet(WpNr='1',WoOper='00000002')",
"type": "ZLOTO_POC_SRV.WorkPermit_itm"
},
"WpNr": "1",
"WoOper": "00000002",
"Desc": "Second item description",
"CreateUser": "TDPO",
"ChangeUser": "TDPO"
}]
}
}
}
I believe you might have to look at your models, for they might need to be updated to handle the structures.
For it took me a few tries but there seems to be a redundancy in the model; as I named it, Result. For once I made that class have all possible properties, it became the go-to class for both levels; it then deserialized.
Here is my deserialization line:
var sap = JsonSerializer.Deserialize<SAPData>(GetData());
Models
public class SAPData
{
public Result d { get; set; }
}
public class Result
{
public __metadata __metadata { get; set; }
public string WpNr { get; set; }
public string WoNr { get; set; }
public string Desc1 { get; set; }
public string Desc2 { get; set; }
public string Loc1 { get; set; }
public string Loc2 { get; set; }
public string Execution { get; set; }
public string ExecDept { get; set; }
public string ExecComp { get; set; }
public string SupExec { get; set; }
public string SupExecTel { get; set; }
public string VpkInstr { get; set; }
public string VpkInstrTel { get; set; }
public string WorkSup { get; set; }
public string WorkSupTel { get; set; }
public string Status { get; set; }
public string ValidFrom { get; set; }
public string ValidTo { get; set; }
public string CreateUser { get; set; }
public string ChangeUser { get; set; }
public string WoOper { get; set; }
public string Desc { get; set; }
public WorkPermit_hdr_itm_nav WorkPermit_hdr_itm_nav { get; set; }
}
public class __metadata
{
public string id { get; set; }
public string uri { get; set; }
public string type { get; set; }
}
public class WorkPermit_hdr_itm_nav
{
public List<Result> results { get; set; }
}
Test JSON
public string GetData()
{
return #"{
""d"": {
""__metadata"": {
""id"": ""http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_hdrSet(\u00271\u0027)"",
""uri"": ""http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_hdrSet(\u00271\u0027)"",
""type"": ""ZLOTO_POC_SRV.WorkPermit_hdr""
},
""WpNr"": ""1"",
""WoNr"": ""123456789"",
""Desc1"": ""FLOP12"",
""Desc2"": ""No ieda"",
""Loc1"": """",
""Loc2"": """",
""Execution"": ""I"",
""ExecDept"": ""\u0027t smoorkot"",
""ExecComp"": """",
""SupExec"": ""Big boss"",
""SupExecTel"": ""\u002B32474895623"",
""VpkInstr"": ""Mr unknown"",
""VpkInstrTel"": ""\u002B32474895624"",
""WorkSup"": ""N/A"",
""WorkSupTel"": ""\u002B32474895625"",
""Status"": """",
""ValidFrom"": null,
""ValidTo"": null,
""CreateUser"": """",
""ChangeUser"": """",
""WorkPermit_hdr_itm_nav"": {
""results"": [
{
""__metadata"": {
""id"": ""http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_itmSet(WpNr=\u00271\u0027,WoOper=\u002700000001\u0027)"",
""uri"": ""http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_itmSet(WpNr=\u00271\u0027,WoOper=\u002700000001\u0027)"",
""type"": ""ZLOTO_POC_SRV.WorkPermit_itm""
},
""WpNr"": ""1"",
""WoOper"": ""00000001"",
""Desc"": ""First iitem desc"",
""CreateUser"": ""TDPO"",
""ChangeUser"": ""TDPO""
},
{
""__metadata"": {
""id"": ""http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_itmSet(WpNr=\u00271\u0027,WoOper=\u002700000002\u0027)"",
""uri"": ""http://xxx:8000/sap/opu/odata/sap/ZLOTO_POC_SRV/WorkPermit_itmSet(WpNr=\u00271\u0027,WoOper=\u002700000002\u0027)"",
""type"": ""ZLOTO_POC_SRV.WorkPermit_itm""
},
""WpNr"": ""1"",
""WoOper"": ""00000002"",
""Desc"": ""Second item description"",
""CreateUser"": ""TDPO"",
""ChangeUser"": ""TDPO""
}
]
}
}
}
";
}
I am trying to deserialize this JSON, but I keep getting errors. Can someone please help me? Where did I make a mistake?
JSON:
{
"totalItems": 63,
"items": [
{
"id": 100039812,
"group": {
"code": "DD",
"description": "Delivery Documents"
},
"type": {
"code": "READ",
"description": "Logs"
},
"reference": "ARLDR",
"date": "2015-03-24T00:00:00",
"description": "ALogs",
"notes": "",
"lastUpdateDate": "2015-03-24T14:06:42.063",
"location": "BOX A001",
"metadata": {}
},
{
"id": 100039813,
"group": {
"code": "DD",
"description": "Delivery Documents"
},
"type": {
"code": "BL",
"description": "Logbooks"
},
"reference": "BALB",
"date": "2015-03-24T00:00:00",
"description": "Logbooks",
"notes": "",
"lastUpdateDate": "2015-03-24T14:07:42.44",
"location": "BOX A001",
"metadata": {}
}
]
}
public class Documents
{
public int totalItems { get; set; }
public List<doc_items> items { get; set; }
}
public class doc_items
{
public int id { get; set; }
public List<group_items> group { get; set; }
public List<type_items> type { get; set; }
public string reference { get; set; }
public string date { get; set; }
public string description { get; set; }
public string notes { get; set; }
public string lastUpdateDate { get; set; }
public string location { get; set; }
public List<metadata_list> metadata { get; set; }
}
public class group_items
{
public string code { get; set; }
public string description { get; set; }
}
public class type_items
{
public string code { get; set; }
public string description { get; set; }
}
public class metadata_list
{
}
Then I call this:
Documents myDocuments = JsonConvert.DeserializeObject<Documents>(responsetext.ToString());
and receive the following error:
Error: Newtonsoft.Json.JsonSerializationException:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type System.Collections.Generic.List`1[AerData.Ranorex.Web.Records.API_Documents+Documents]' because the type requires a JSON array (e.g. [...
On the contrary 'group', 'type' and 'metadata' are not arrays so modify your class to:
public class doc_items
{
public int id { get; set; }
public group_items group { get; set; }
public type_items type { get; set; }
public string reference { get; set; }
public string date { get; set; }
public string description { get; set; }
public string notes { get; set; }
public string lastUpdateDate { get; set; }
public string location { get; set; }
public metadata_list metadata { get; set; }
}
Given from the definition of the Documents class, the group property of an doc_items has to be an array. In your given JSON it's an object. The same holds for the type property
I recommend using a converter like this: http://json2csharp.com/#
Try this:
class Program
{
static void Main(string[] args)
{
var sr = new StreamReader("json.json");
var jsonText = sr.ReadToEnd();
Documents myDocuments = JsonConvert.DeserializeObject<Documents>(jsonText);
}
}
public class group_items
{
public string code { get; set; }
public string description { get; set; }
}
public class type_items
{
public string code { get; set; }
public string description { get; set; }
}
public class metadata_list
{
}
public class doc_items
{
public int id { get; set; }
public group_items GroupItems { get; set; }
public type_items TypeItems { get; set; }
public string reference { get; set; }
public string date { get; set; }
public string description { get; set; }
public string notes { get; set; }
public string lastUpdateDate { get; set; }
public string location { get; set; }
public metadata_list MetadataList { get; set; }
}
public class Documents
{
public int totalItems { get; set; }
public List<doc_items> items { get; set; }
}
Your data file json.json
{
"totalItems": 63,
"items": [
{
"id": 100039812,
"group": {
"code": "DD",
"description": "Delivery Documents"
},
"type": {
"code": "READ",
"description": "Logs"
},
"reference": "ARLDR",
"date": "2015-03-24T00:00:00",
"description": "ALogs",
"notes": "",
"lastUpdateDate": "2015-03-24T14:06:42.063",
"location": "BOX A001",
"metadata": { }
},
{
"id": 100039813,
"group": {
"code": "DD",
"description": "Delivery Documents"
},
"type": {
"code": "BL",
"description": "Logbooks"
},
"reference": "BALB",
"date": "2015-03-24T00:00:00",
"description": "Logbooks",
"notes": "",
"lastUpdateDate": "2015-03-24T14:07:42.44",
"location": "BOX A001",
"metadata": { }
}
]
}
I have a Json response:
{
"external_id": null,
"id": 37974,
"confirmation_number": "355684938",
"state": "unauthorized",
"first_name": "",
"last_name": "mack",
"email": "teja#fareportal.com",
"room_code": null,
"room_description": null,
"start_on": "2014-11-17",
"end_on": "2014-11-18",
"property_id": 666,
"loyalty_number": null,
"average_daily_rate": null,
"room_charges": "$0.00",
"property": {
"id": 666,
"name": "Comfort Inn Gaslamp Convention Center",
"phone": "1 619 238-4100",
"full_address": "660 G Street, San Diego, CA, 92101, US",
"latitude": 32.712823,
"longitude": -117.158607,
"checkout_time": null,
"time_zone": "America/Los_Angeles",
"address": {
"street": "660 G Street",
"city": "San Diego",
"region": "CA",
"postal_code": "92101",
"country_code": "US"
},
"links": [
{
"rel": "vertical_photo",
"href": null,
"version": "retina"
},
{
"rel": "vertical_photo",
"href": null,
"version": "standard"
},
{
"rel": "horizontal_photo",
"href": null,
"version": "retina"
},
{
"rel": "horizontal_photo",
"href": null,
"version": "standard"
},
{
"rel": "reservations",
"href": "https://partners-staging.checkmate.io/properties/666/reservations"
}
]
},
"links": [
{
"rel": "self",
"href": "https://partners-staging.checkmate.io/reservations/37974"
}
]
}
I have to assign the values in class .
I have created the class on http://json2csharp.com/ .
The classes are :
public class Address
{
public string street { get; set; }
public string city { get; set; }
public string region { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
}
public class Link
{
public string rel { get; set; }
public string href { get; set; }
public string version { get; set; }
}
public class Property
{
public int id { get; set; }
public string name { get; set; }
public string phone { get; set; }
public string full_address { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public object checkout_time { get; set; }
public string time_zone { get; set; }
public Address address { get; set; }
public List<Link> links { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
}
public class RootObject
{
public object external_id { get; set; }
public int id { get; set; }
public string confirmation_number { get; set; }
public string state { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string email { get; set; }
public object room_code { get; set; }
public object room_description { get; set; }
public string start_on { get; set; }
public string end_on { get; set; }
public int property_id { get; set; }
public object loyalty_number { get; set; }
public object average_daily_rate { get; set; }
public string room_charges { get; set; }
public Property property { get; set; }
public List<Link2> links { get; set; }
}
How can we de serialize the data from json and assign in those class.
Thanks in advance.
Using JSON.NET
var root = JsonConvert.DeserializeObject<RootObject>(json);
using System.Web.Script.Serialization;
JavaScriptSerializer objectJS = new JavaScriptSerializer();
RootObject objectRootObject = new RootObject();
objectRootObject = objectJS.Deserialize<RootObject>(Your JSon String);
I need to deserialize this JSON:
{
"kind": "plus#activityFeed",
"etag": "\"JOoejvNXXEWjTp1RkvR4kuXnXWE/vHWQzjhUi3hCdDLiE71KtrP47bA\"",
"nextPageToken": "CAIQ-MGf9Z72tgIgAigC",
"title": "Google+ List of Activities for Collection PUBLIC",
"updated": "2013-05-02T01:13:01.244Z",
"items": [
{
"kind": "plus#activity",
"etag": "\"JOoejvNXXEWjTp1RkvR4kuXnXWE/AgB1ExcMum9t0T-ruWqtunO3kS0\"",
"title": "Gene gets creative - and slightly offensive - in a table-setting competition.",
"published": "2013-05-02T01:13:01.244Z",
"updated": "2013-05-02T01:13:01.244Z",
"id": "z13dezeopsqzg3y4404chhh52xnhepqxxdo",
"url": "link",
"actor": {
"id": "102458557561671030191",
"displayName": "Bob's Burgers",
"url": "link",
"image": {
"url": "link"
}
},
"verb": "post",
"object": {
"objectType": "note",
"content": "Gene gets creative - and slightly offensive - in a table-setting competition.",
"url": "link",
"replies": {
"totalItems": 0,
"selfLink": "link"
},
"plusoners": {
"totalItems": 19,
"selfLink": "link"
},
"resharers": {
"totalItems": 2,
"selfLink": "link"
},
"attachments": [
{
"objectType": "article",
"displayName": "Table-Scaping from \"Boyz 4 Now\" | BOB'S BURGERS | ANIMATION on FOX",
"content": "",
"url": "link",
"image": {
"url": "link",
"type": "image/jpeg",
"height": 150,
"width": 150
},
"fullImage": {
"url": "link",
"type": "image/jpeg"
}
}
]
},
"provider": {
"title": "Google+"
},
"access": {
"kind": "plus#acl",
"description": "Public",
"items": [
{
"type": "public"
}
]
}
},
{
"kind": "plus#activity",
"etag": "\"JOoejvNXXEWjTp1RkvR4kuXnXWE/4ijLLkjecVl_dKuv7sJ7CCnuQnc\"",
"title": "Did you recognize New Girl star Max Greenfield as the voice of \"Boyz 4 Now\" heartthrob, Boo Boo, on last...",
"published": "2013-05-02T01:12:46.516Z",
"updated": "2013-05-02T01:12:46.516Z",
"id": "z122x1ejvrz2uj4s323ffdcrgvephrjeh",
"url": "link",
"actor": {
"id": "102458557561671030191",
"displayName": "Bob's Burgers",
"url": "link",
"image": {
"url": "link"
}
},
"verb": "post",
"object": {
"objectType": "note",
"content": "Did you recognize New Girl star Max Greenfield as the voice of "Boyz 4 Now" heartthrob, Boo Boo, on last Sunday's episode of Bob's Burgers?",
"url": "link",
"replies": {
"totalItems": 3,
"selfLink": "link"
},
"plusoners": {
"totalItems": 8,
"selfLink": "link"
},
"resharers": {
"totalItems": 0,
"selfLink": "link"
},
"attachments": [
{
"objectType": "article",
"displayName": "Exclusive: Bob's Burgers First Look: New Girl's Max Greenfield Is the Boyband-er of Your Dreams",
"content": "No one can play a lovable douchebag like Max Greenfield on New Girl, but did you also know he can...",
"url": "link",
"image": {
"url": "link",
"type": "image/jpeg",
"height": 150,
"width": 150
},
"fullImage": {
"url": "link",
"type": "image/jpeg"
}
}
]
},
"provider": {
"title": "Google+"
},
"access": {
"kind": "plus#acl",
"description": "Public",
"items": [
{
"type": "public"
}
]
}
}
]
}
This is the code I use to deserialize:
var rootObject = JsonConvert.DeserializeObject<Classes.activities.RootObject>(e.Result);
foreach (var activity in rootObject.items)
{
}
And these are the classes:
public class Image
{
public string url { get; set; }
}
public class Actor
{
public string id { get; set; }
public string displayName { get; set; }
public string url { get; set; }
public Image image { get; set; }
}
public class Replies
{
public int totalItems { get; set; }
public string selfLink { get; set; }
}
public class Plusoners
{
public int totalItems { get; set; }
public string selfLink { get; set; }
}
public class Resharers
{
public int totalItems { get; set; }
public string selfLink { get; set; }
}
public class Image2
{
public string url { get; set; }
public string type { get; set; }
public int height { get; set; }
public int width { get; set; }
}
public class Embed
{
public string url { get; set; }
public string type { get; set; }
}
public class FullImage
{
public string url { get; set; }
public string type { get; set; }
}
public class Attachment
{
public string objectType { get; set; }
public string displayName { get; set; }
public string content { get; set; }
public string url { get; set; }
public Image2 image { get; set; }
public Embed embed { get; set; }
public FullImage fullImage { get; set; }
}
public class Object
{
public string objectType { get; set; }
public string content { get; set; }
public string url { get; set; }
public Replies replies { get; set; }
public Plusoners plusoners { get; set; }
public Resharers resharers { get; set; }
public List<Attachment> attachments { get; set; }
}
public class Provider
{
public string title { get; set; }
}
public class Item2
{
public string type { get; set; }
}
public class Access
{
public string kind { get; set; }
public string description { get; set; }
public List<Item2> items { get; set; }
}
public class Item
{
public string kind { get; set; }
public string etag { get; set; }
public string title { get; set; }
public string published { get; set; }
public string updated { get; set; }
public string id { get; set; }
public string url { get; set; }
public Actor actor { get; set; }
public string verb { get; set; }
public Object #object { get; set; }
public Provider provider { get; set; }
public Access access { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public string etag { get; set; }
public string nextPageToken { get; set; }
public string title { get; set; }
public string updated { get; set; }
public List<Item> items { get; set; }
}
Now the problem is that I can't access any item after activity.#object.attachment
You could try apply a JsonProperty attribute to properties which are reserved keywords in .Net (such as object, in your case)
i.e.
[JsonObject]
public class Item
{
[JsonProperty(PropertyName = "kind")]
public string kind { get; set; }
...
[JsonProperty(PropertyName = "object")]
public Object TheObject { get; set; }
...
}