DeSerialize Json into Class object - c#

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);

Related

Data transfer from one object class to another with different format and properties name

I am stuck in a problem since more than a week. I am using C# and I am doing Zoho Integration with my application, and I am passing JSON string from my application to Middle layer which will call Zoho API and send required JSON format to insert records in zoho module.
I am sending JSON from my application is :
{
"TonerRequestID": 0,
"CustAccountId": 0,
"CRMAccountId": null,
"CRMODId": null,
"BillTo": "200173",
"Asset": null,
"AssetId": null,
"CreatedDateTime": null,
"CreatedIP": null,
"CreatedBy": null,
"ModifiedBy": null,
"ModifiedIP": null,
"ModifiedDateTime": null,
"Remarks": "",
"CurrStockQty": 0,
"CurrReqQty": 0,
"PrevColorCount": 0,
"PrevBWCount": 0,
"Attachment1": null,
"Attachment1StoredPath": null,
"Serial": "Manual Byepass MB-504 -VIKAS56789 ",
"SerialId": "371.0",
"lsttonerRequestDetails": [
{
"TonerRequestID": "0",
"CRMProductID": null,
"AssetId": null,
"ItemCode": "80636.0",
"CurrStockQty": "4",
"CreatedDateTime": null,
"RequiredQty": "5",
"PrevStockQty": "12",
"PrevRequiredQty": "3",
"dtLastReqDate": null
},
{
"TonerRequestID": "0",
"CRMProductID": null,
"AssetId": null,
"ItemCode": "80637.0",
"CurrStockQty": "8",
"CreatedDateTime": null,
"RequiredQty": "9",
"PrevStockQty": "6",
"PrevRequiredQty": "7",
"dtLastReqDate": null
},
{
"TonerRequestID": "0",
"CRMProductID": null,
"AssetId": null,
"ItemCode": "80638.0",
"CurrStockQty": "12",
"CreatedDateTime": null,
"RequiredQty": "13",
"PrevStockQty": "10",
"PrevRequiredQty": "11",
"dtLastReqDate": null
},
{
"TonerRequestID": "0",
"CRMProductID": null,
"AssetId": null,
"ItemCode": "80639.0",
"CurrStockQty": "16",
"CreatedDateTime": null,
"RequiredQty": "17",
"PrevStockQty": "14",
"PrevRequiredQty": "15",
"dtLastReqDate": null
},
{
"TonerRequestID": "0",
"CRMProductID": null,
"AssetId": null,
"ItemCode": "80640.0",
"CurrStockQty": "20",
"CreatedDateTime": null,
"RequiredQty": "21",
"PrevStockQty": "18",
"PrevRequiredQty": "19",
"dtLastReqDate": null
}
]
}
Now I want to manipulate this JSON and create actual format which ZOHO module wants. i.e.
{
"data": [
{
"Layout": {
"name" : "Toner",
"id": "207069000003373769"
},
"Owner": {
"id": "207069000001122001"
},
"Asset": {
"id": "207069000025605299"
},
"Account_Name": {
"id": "207069000019985406"
},
"Related_To": {
"id": "207069000026124057"
},
"Contact": {
"id": "207069000026124057"
},
"Current_Black_and_white_Count": "12",
"Current_Color_Count": "12",
"Current_Reading1": "12",
"Current_Reading": "12",
"Last_Spare_Request_Click_Count": "12",
"Last_Spare_Request_Date": "2022-06-09",
"Minimum_Yield": "12",
"No_of_comments": "12",
"Order_No": "12",
"Previous_Reading": "12",
"Previous_Reading1": "12",
"Subject": "Azeem Test Details 2",
"System_Yield": "12",
"Current_Reading_Total": "12",
"Previous_Reading_Total": "12",
"Priority": "Medium",
"Requested_Date_Time": "2022-06-17T18:00:00+05:30",
"Solution": "Complex functionality",
"Standard_Yield": "12",
"Actual_Yield": "12",
"Case_Origin": "12",
"Status": "NEW",
"Toner_Request_Details": [{
"Current_Stock1": "456",
"Description": "456",
"Item_Code1": {"id":"207069000024880067"},
"Quantity_Req": "456"
},
{
"Current_Stock1": "789",
"Description": "789",
"Item_Code1": {"id":"207069000024880067"},
"Quantity_Req": "789"
}
]
}
]
}
I want to make above Zoho JSON structure from JSON of my application which I put in start. As there are difference in every field name, I am using mapper table to map fields from both JSON. like :
Image: Fields Mapping for both JSON
So what I want to do is, I will loop through the source json fields and put a condition to match source JSON fields and Destination fields and if name matched I will assign value of source JSON field to Destination field.
I have defined a class to Deserialize source json and defined a class to put values in it and serialize to JSON and send to ZOHO.
Source Class :
public class TonerRequestMaster
{
public Int64 TonerRequestID { get; set; }
public Int64 CustAccountId { get; set; }
public string CRMAccountId { get; set; }
public string CRMODId { get; set; }
public string BillTo { get; set; }
public string Asset { get; set; }
public string AssetId { get; set; }
public DateTime? CreatedDateTime { get; set; }
public string CreatedIP { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public string ModifiedIP { get; set; }
public DateTime? ModifiedDateTime { get; set; }
public string Remarks { get; set; }
public decimal CurrStockQty { get; set; }
public decimal CurrReqQty { get; set; }
public decimal PrevColorCount { get; set; }
public decimal PrevBWCount { get; set; }
public string Attachment1 { get; set; }
public string Attachment1StoredPath { get; set; }
public string Serial { get; set; }
public string SerialId { get; set; }
public List<TonerRequestDetails> lsttonerRequestDetails { get; set; }
}
public class TonerRequestDetails
{
public string TonerRequestID { get; set; }
public string CRMProductID { get; set; }
public string AssetId { get; set; }
public string ItemCode { get; set; }
public string CurrStockQty { get; set; }
public DateTime? CreatedDateTime { get; set; }
public string RequiredQty { get; set; }
public string PrevStockQty { get; set; }
public string PrevRequiredQty { get; set; }
public string dtLastReqDate { get; set; }
}
Destination Class :
{
public class AccountName
{
public string id { get; set; }
}
public class Asset
{
public string id { get; set; }
}
public class Contact
{
public string id { get; set; }
}
public class Datum
{
public Layout Layout { get; set; }
public Owner Owner { get; set; }
public Asset Asset { get; set; }
public AccountName Account_Name { get; set; }
public RelatedTo Related_To { get; set; }
public Contact Contact { get; set; }
public string Current_Black_and_white_Count { get; set; }
public string Current_Color_Count { get; set; }
public string Current_Reading1 { get; set; }
public string Current_Reading { get; set; }
public string Last_Spare_Request_Click_Count { get; set; }
public string Last_Spare_Request_Date { get; set; }
public string Minimum_Yield { get; set; }
public string No_of_comments { get; set; }
public string Order_No { get; set; }
public string Previous_Reading { get; set; }
public string Previous_Reading1 { get; set; }
public string Subject { get; set; }
public string System_Yield { get; set; }
public string Current_Reading_Total { get; set; }
public string Previous_Reading_Total { get; set; }
public string Priority { get; set; }
public DateTime Requested_Date_Time { get; set; }
public string Solution { get; set; }
public string Standard_Yield { get; set; }
public string Actual_Yield { get; set; }
public string Case_Origin { get; set; }
public string Status { get; set; }
public List<TonerRequestDetail> Toner_Request_Details { get; set; }
}
public class ItemCode1
{
public string id { get; set; }
}
public class Layout
{
public string name { get; set; }
public string id { get; set; }
}
public class Owner
{
public string id { get; set; }
}
public class RelatedTo
{
public string id { get; set; }
}
public class TonerRequestZoho
{
public List<Datum> data { get; set; }
}
public class TonerRequestDetail
{
public string Current_Stock1 { get; set; }
public string Description { get; set; }
public ItemCode1 Item_Code1 { get; set; }
public string Quantity_Req { get; set; }
}
}
Please help me in this, it would be appreciated.
it would help if you created your c# models hierarchy like the JSON, and you have to make the models with same name as the JSON, for example:
public class Layout
{
public string Name { get; set; }
public long Id { get; set; }
}
public class Owner
{
public long Id { get; set; }
}
public class Zoho
{
public List<ZohoModel> Data { get; set; }
}
public class ZohoModel
{
public Layout Layout { get; set; }
public Owner Owner { get; set; }
public string Current_Black_and_white_Count { get; set; }
.
.
.
}

How do I deserialize this Json (Header + Item from SAP) into a model

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""
}
]
}
}
}
";
}

Deserialize multiple json into object c#

I'm trying to deserialize a json string from a API call with multiple objects but without much success.
JSON:
#{
"purchaseOrders": [
{
"supplierId": "500",
"currencyCode": "EUR",
"companyId": "LALA",
"companyName": "LALA",
"purchaseOrderLines": [
{
"lineNumber": "10",
"itemNumber": "255",
"itemDescription": "TestItem2",
"unitPrice": 24.64,
"quantity": 2,
"isServiceBased": false,
"taxIndicator1": "LAAA5",
"taxIndicator2": "4",
"unit": "-",
"deliveryLines": [],
"supplierItems": [],
"isActive": true
},
{
"lineNumber": "20",
"itemNumber": "5555555",
"itemDescription": "3test, Ind",
"unitPrice": 32.56,
"quantity": 2,
"isServiceBased": false,
"taxIndicator1": "LAAA5",
"taxIndicator2": "4",
"unit": "-",
"deliveryLines": [],
"supplierItems": [],
"isActive": true
}
],
"orderIdentifier": "261656",
"supplierName": "Lopes BVBA",
"orderType": "T",
"isActive": true
},
{
"supplierId": "5555",
"currencyCode": "EUR",
"companyId": "API",
"companyName": "LALA2",
"purchaseOrderLines": [
{
"lineNumber": "1",
"itemNumber": "448",
"itemDescription": "TestItem",
"unitPrice": 1563.23117,
"quantity": 1,
"isServiceBased": false,
"unit": "-",
"deliveryLines": [],
"supplierItems": [],
"isActive": true
},
{
"lineNumber": "2",
"itemNumber": "5551",
"itemDescription": "Test",
"unitPrice": 524.92539,
"quantity": 1,
"isServiceBased": false,
"unit": "-",
"deliveryLines": [],
"supplierItems": [],
"isActive": true
}
],
"orderIdentifier": "84615",
"supplierName": "CLopes.",
"orderType": "T",
"isActive": true
}]
I created the following model classes:
public class purchaseOrder
{
public string supplierId { get; set; }
public string currencyCode { get; set; }
public string companyId { get; set; }
public string companyName { get; set; }
public List<purchaseOrderLines> purchaseOrderLines { get; set; }
public double orderIdentifier { get; set; }
public string supplierName { get; set; }
public string Ordertype { get; set; }
public bool isActive { get; set; }
}
public class purchaseOrderLines
{
public int lineNumber { get; set; }
public string itemnumber { get; set; }
public string itemDescription { get; set; }
public double unitPrice { get; set; }
public int quantity { get; set; }
public bool isServiceBased { get; set; }
public string unit { get; set; }
public List<deliveryLines> deliveryLines { get; set; }
public string[] supplierItems { get; set; }
public bool isActive { get; set; }
}
public class deliveryLines
{
public int deliveredQuantity { get; set; }
public DateTime? deliveredDate { get; set; }
public string deliveryNote { get; set; }
public bool isActive { get; set; }
}
I tried doing this by deserializing the string into a purchaseOrder
(purchaseOrder purchaseOrderobject = JsonConvert.DeserializeObject<purchaseOrder >(json);)
but with no success. I think maybe I have to make use of a dictionary for this but I'm not completely sure how to do that.
Is there a way to do this by getting the json objects one by one an deserializing them like in the following link?
Deserialize single object
You said "with no success", so it's unclear if there's an error or what. But...
I think the issue is your root object. I ran your JSON through json2csharp.com and this is what it came up with:
public class PurchaseOrderLine
{
public string lineNumber { get; set; }
public string itemNumber { get; set; }
public string itemDescription { get; set; }
public double unitPrice { get; set; }
public int quantity { get; set; }
public bool isServiceBased { get; set; }
public string taxIndicator1 { get; set; }
public string taxIndicator2 { get; set; }
public string unit { get; set; }
public List<object> deliveryLines { get; set; }
public List<object> supplierItems { get; set; }
public bool isActive { get; set; }
}
public class PurchaseOrder
{
public string supplierId { get; set; }
public string currencyCode { get; set; }
public string companyId { get; set; }
public string companyName { get; set; }
public List<PurchaseOrderLine> purchaseOrderLines { get; set; }
public string orderIdentifier { get; set; }
public string supplierName { get; set; }
public string orderType { get; set; }
public bool isActive { get; set; }
}
public class RootObject
{
public List<PurchaseOrder> purchaseOrders { get; set; }
}
Try that with var root = JsonConvert.DeserializeObject<RootObject>(json);
You JSON is an array of purchase order, so you need to deserialize it into a list
var list = JsonConvert.DeserializeObject<List<purchaseOrder>>(json);)

How to deserialize this JSON with JsonConvert.DeserializeObject

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": { }
}
]
}

How can i extract PayPal Response C#

How can i extract this data in c#, in order to get all elements that i need:
{ "id": "PAY-6A414645MC669653MKPB2WCI", "create_time": "2014-07-14T10:03:53Z", "update_time": "2014-07-14T10:05:09Z", "intent": "sale", "payer": { "payment_method": "paypal", "payer_info": { "email": "severiano.testes#gmail.com", "first_name": "tester", "last_name": "tester", "payer_id": "MSQ6UB55W52N6", "shipping_address": { "line1": "1 Main Terrace", "line2": "", "city": "Wolverhampton", "country_code": "GB", "postal_code": "W12 4LQ", "state": "West Midlands" } } }, "transactions": [ { "amount": { "currency": "EUR", "total": "54.00", "details": { "subtotal": "54.00" } }, "description": "Transaction Description", "item_list": { "items": [ { "quantity": "1", "name": "Project Submission (featured)", "price": "54.00", "currency": "EUR", "sku": "64866" } ], "shipping_address": { "recipient_name": "tester tester", "line1": "1 Main Terrace", "line2": "", "city": "Wolverhampton", "country_code": "GB", "postal_code": "W12 4LQ", "state": "West Midlands" } }, "related_resources": [ { "sale": { "id": "4VV61663EL511901P", "create_time": "2014-07-14T10:03:53Z", "update_time": "2014-07-14T10:05:09Z", "amount": { "currency": "EUR", "total": "54.00" }, "state": "pending", "parent_payment": "PAY-6A414645MC669653MKPB2WCI", "links": [ { "href": "https://api.sandbox.paypal.com/v1/payments/sale/4VV61663EL511901P", "rel": "self", "method": "GET" }, { "href": "https://api.sandbox.paypal.com/v1/payments/sale/4VV61663EL511901P/refund", "rel": "refund", "method": "POST" }, { "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-6A414645MC669653MKPB2WCI", "rel": "parent_payment", "method": "GET" } ] } } ] } ], "state": "pending", "links": [ { "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-6A414645MC669653MKPB2WCI", "rel": "self", "method": "GET" } ] }
I've tried to send to jquery function but not successfull.
I've tried this aswell:
JObject.Parse(HttpContext.Current.Items["ResponseJson"]).GetValue("id");
this works but only to one value, not all that i want
you have to declare class like
public class Rootobject
{
public string id { get; set; }
public DateTime create_time { get; set; }
public DateTime update_time { get; set; }
public string intent { get; set; }
public Payer payer { get; set; }
public Transaction[] transactions { get; set; }
public string state { get; set; }
public Link1[] links { get; set; }
}
public class Payer
{
public string payment_method { get; set; }
public Payer_Info payer_info { get; set; }
}
public class Payer_Info
{
public string email { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string payer_id { get; set; }
public Shipping_Address shipping_address { get; set; }
}
public class Shipping_Address
{
public string line1 { get; set; }
public string line2 { get; set; }
public string city { get; set; }
public string country_code { get; set; }
public string postal_code { get; set; }
public string state { get; set; }
}
public class Transaction
{
public Amount amount { get; set; }
public string description { get; set; }
public Item_List item_list { get; set; }
public Related_Resources[] related_resources { get; set; }
}
public class Amount
{
public string currency { get; set; }
public string total { get; set; }
public Details details { get; set; }
}
public class Details
{
public string subtotal { get; set; }
}
public class Item_List
{
public Item[] items { get; set; }
public Shipping_Address1 shipping_address { get; set; }
}
public class Shipping_Address1
{
public string recipient_name { get; set; }
public string line1 { get; set; }
public string line2 { get; set; }
public string city { get; set; }
public string country_code { get; set; }
public string postal_code { get; set; }
public string state { get; set; }
}
public class Item
{
public string quantity { get; set; }
public string name { get; set; }
public string price { get; set; }
public string currency { get; set; }
public string sku { get; set; }
}
public class Related_Resources
{
public Sale sale { get; set; }
}
public class Sale
{
public string id { get; set; }
public DateTime create_time { get; set; }
public DateTime update_time { get; set; }
public Amount1 amount { get; set; }
public string state { get; set; }
public string parent_payment { get; set; }
public Link[] links { get; set; }
}
public class Amount1
{
public string currency { get; set; }
public string total { get; set; }
}
public class Link
{
public string href { get; set; }
public string rel { get; set; }
public string method { get; set; }
}
public class Link1
{
public string href { get; set; }
public string rel { get; set; }
public string method { get; set; }
}
Then you have to use using Newtonsoft.Json; for DeserializeObject like
var Data = JsonConvert.DeserializeObject<Rootobject>("your Json string");
you can access the property using Data
O/P looks like
You need to just make a mapping object and then deserialize the json
public class PaymentResponse
{
public string id { get; set; }
public DateTime create_time { get; set; }
public DateTime update_time { get; set; }
public string intent {get; set; }
public Payer payer{get; set; }
}
public class Payer
{
public string payment_method {get;set;}
public PayerInfo payer_info {get;set;}
}
public class PayerInfo
{
public string email { get; set; }
public string first_name { get; set; }
}
Don't have time to add all of the values but if you use a json parser so you can see the response easier. I prefer this one.
http://json.parser.online.fr/
Then simply deserialize the json response with the below
var paymentResponse = new JavaScriptSerializer().Deserialize<PaymentResponse>(jsonString);

Categories