Deserialize multiple json into object c# - 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);)

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 to use json.net for asp.net core model binding on POST requests?

I've seen this other question with no answer.
I need to deserialize with newtonsoft because I have circular references loop handling when sending the data to the client:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
This produces JSON objects with $id and $ref that are making the model binder fail on POST requests when the modified data comes back.
Note that I have a pretty complex object model as you can se below:
{
"$id": "1",
"vehiculeId": 359586015016459,
"companyId": 1,
"phoneNumber": "0614407055",
"hardwareId": 866857042994208,
"gpsBoxType": 29,
"name": "Redmi Note 6 Pro Olivier M",
"iconId": 33554432,
"gpsBoxTrackingDelay": 1,
"rowEnabled": true,
"dbInsertTime": 1549527854940,
"device": {
"$id": "2",
"imei": 866857042994208,
"brand": "Xiaomi",
"model": "Redmi Note 6 Pro",
"name": "Redmi Olivier",
"registration": {
"$id": "3",
"imei": 866857042994208,
"companyId": 1,
"latestRegistrationStatusChangeDate": 1556168520000,
"registrationStatus": 3,
"imeiNavigation": {
"$ref": "2"
}
}
},
"vehiculeGpsBoxInfo": {
"$id": "4",
"vehiculeId": 359586015016459,
"currentDelay": 0,
"normalTrackingMode": 2,
"timeModeDelay": 60000,
"smartModeDelay": 5000,
"smartModeDistance": 100,
"connected": false,
"heartBeatPeriod": 1200,
"insureCoherence": false,
"killHedgehog": true,
"lastCommunicationTime": 1563519489853,
"vehiculeConfiguration": 111,
"updateStatus": 0,
"vehicule": {
"$ref": "1"
},
"vehiculeConfigurationNavigation": {
"$id": "5",
"configurationId": 111,
"configName": "PTIMobileTest",
"masterName": "PTIMobileTest",
"master": "1.0.32",
"firmware": "",
"system": "",
"gpsBoxType": 29,
"vehiculeGpsBoxInfoBoardConfigurationNavigation": [],
"vehiculeGpsBoxInfoVehiculeConfigurationNavigation": [
{
"$ref": "4"
}
]
}
},
"fleetDetail": [
{
"$id": "6",
"fleetDetailId": 27494,
"fleetId": 3216,
"vehiculeId": 359586015016459,
"rowEnabled": true,
"fleet": {
"$id": "7",
"fleetId": 3216,
"companyId": 1,
"name": "RTEProtect",
"rowEnabled": true,
"fleetDetailFleet": [
{
"$id": "8",
"fleetDetailId": 25988,
"fleetId": 3216,
"vehiculeId": 359586014995819,
"rowEnabled": true,
"fleet": {
"$ref": "7"
},
"vehicule": {
"$id": "9",
"vehiculeId": 359586014995819,
"companyId": 1,
"phoneNumber": " ",
"hardwareId": 358240051111110,
"gpsBoxType": 29,
"category": "PTI",
"name": "PTI Emulateur Fred",
"iconId": 33571442,
"gpsBoxTrackingDelay": 1,
"addressProtocol": 0,
"rowEnabled": true,
"dbInsertTime": 1448607218600,
"device": {
"$id": "10",
"imei": 358240051111110,
"brand": "Unknown",
"model": "PTI Emulateur",
"name": "PTI Emulateur Fred",
"registration": {
"$id": "11",
"imei": 358240051111110,
"companyId": 1,
"latestRegistrationStatusChangeDate": 1556169720000,
"registrationStatus": 3,
"imeiNavigation": {
"$ref": "10"
}
}
},
"vehiculeGpsBoxInfo": {
"$id": "12",
"vehiculeId": 359586014995819,
"currentDelay": 0,
"normalTrackingMode": 2,
"timeModeDelay": 60000,
"smartModeDelay": 5000,
"smartModeDistance": 100,
"connected": false,
"heartBeatPeriod": 1200,
"insureCoherence": false,
"killHedgehog": true,
"boardConnected": false,
"lastCommunicationTime": 1558078487030,
"boardLastCommunicationTime": 1485957716897,
"vehiculeConfiguration": 169,
"updateStatus": 0,
"vehicule": {
"$ref": "9"
},
"vehiculeConfigurationNavigation": {
"$id": "13",
"configurationId": 169,
"configName": "SafeProtectSamsungS6",
"masterName": "SafeProtectSamsungS6",
"master": "1.0.2",
"firmware": "",
"system": "",
"gpsBoxType": 29,
"vehiculeGpsBoxInfoBoardConfigurationNavigation": [],
"vehiculeGpsBoxInfoVehiculeConfigurationNavigation": [
{
"$ref": "12"
},
{
"$id": "14",
"vehiculeId": 359586015014836,
"currentDelay": 0,
"normalTrackingMode": 2,
"timeModeDelay": 60000,
"smartModeDelay": 5000,
"smartModeDistance": 100,
"connected": true,
"heartBeatPeriod": 1200,
"insureCoherence": false,
"killHedgehog": true,
"lastCommunicationTime": 1568202416063,
"vehiculeConfiguration": 169,
"updateStatus": 0,
"lastConnexionTime": 1545057192063,
"vehicule": {
"$id": "15",
"vehiculeId": 359586015014836,
"companyId": 1,
"phoneNumber": "+351927853883",
"hardwareId": 356437083709729,
"gpsBoxType": 29,
"name": "Samsung J5 test",
"iconId": 33569462,
"gpsBoxTrackingDelay": 1,
"addressProtocol": 0,
"rowEnabled": true,
"dbInsertTime": 1513945397863,
"device": {
"$id": "16",
"imei": 356437083709729,
"brand": "Samsung",
"model": "J5",
"name": "Test"
},
"vehiculeGpsBoxInfo": {
"$ref": "14"
},
"fleetDetail": [
{
"$id": "17",
"fleetDetailId": 26445,
"fleetId": 3486,
"vehiculeId": 359586015014836,
"rowEnabled": true,
"fleet": {
"$id": "18",
"fleetId": 3486,
"companyId": 1,
"name": "RTE Protect",
"rowEnabled": true,
"fleetDetailFleet": [
{
"$id": "19",
"fleetDetailId": 13251,
"fleetId": 3486,
"vehiculeId": 359586014995819,
"rowEnabled": true,
"fleet": {
"$ref": "18"
},
"vehicule": {
"$ref": "9"
}
},
{
"$id": "20",
"fleetDetailId": 13477,
"fleetId": 3486,
"vehiculeId": 359586014995819,
"rowEnabled": false,
"fleet": {
"$ref": "18"
},
"vehicule": {
"$ref": "9"
}
},
{
"$ref": "17"
}
],
"fleetDetailFleetChildNavigation": []
},
"vehicule": {
"$ref": "15"
}
},
{
"$id": "21",
"fleetDetailId": 27485,
"fleetId": 5536,
"vehiculeId": 359586015014836,
"rowEnabled": true,
"fleet": {
"$id": "22",
"fleetId": 5536,
"companyId": 1,
"name": "SafeProtect",
"rowEnabled": true,
"fleetDetailFleet": [
{
"$ref": "21"
}
],
"fleetDetailFleetChildNavigation": []
},
"vehicule": {
"$ref": "15"
}
}
]
},
"vehiculeConfigurationNavigation": {
"$ref": "13"
}
},
{
"$id": "23",
"vehiculeId": 359586015014947,
"currentDelay": 0,
"normalTrackingMode": 2,
"timeModeDelay": 60000,
"smartModeDelay": 5000,
"smartModeDistance": 100,
"connected": false,
"heartBeatPeriod": 1200,
"insureCoherence": false,
"killHedgehog": true,
"lastCommunicationTime": 1558006034977,
"vehiculeConfiguration": 169,
"updateStatus": 0,
"vehicule": {
"$id": "24",
"vehiculeId": 359586015014947,
"companyId": 1,
"phoneNumber": " ",
"hardwareId": 357011072523992,
"gpsBoxType": 29,
"name": "SafeProtect Céline Pro",
"iconId": 33554432,
"gpsBoxTrackingDelay": 1,
"addressProtocol": 0,
"rowEnabled": true,
"dbInsertTime": 1538134175170,
"device": {
"$id": "25",
"imei": 357011072523992,
"brand": "Samsung",
"model": "S6",
"name": "S6 Céline",
"registration": {
"$id": "26",
"imei": 357011072523992,
"companyId": 1,
"latestRegistrationStatusChangeDate": 1556103600000,
"registrationStatus": 3,
"imeiNavigation": {
"$ref": "25"
}
}
},
"vehiculeGpsBoxInfo": {
"$ref": "23"
},
"fleetDetail": []
},
"vehiculeConfigurationNavigation": {
"$ref": "13"
}
}
]
}
},
"fleetDetail": [
{
"$id": "27",
"fleetDetailId": 26334,
"fleetId": 659,
"vehiculeId": 359586014995819,
"rowEnabled": false,
"fleet": {
"$id": "28",
"fleetId": 659,
"companyId": 1,
"name": "Parc",
"rowEnabled": true,
"fleetDetailFleet": [
{
"$ref": "27"
}
],
"fleetDetailFleetChildNavigation": []
},
"vehicule": {
"$ref": "9"
}
},
{
"$ref": "8"
},
{
"$id": "29",
"fleetDetailId": 25993,
"fleetId": 3216,
"vehiculeId": 359586014995819,
"rowEnabled": false,
"fleet": {
"$ref": "7"
},
"vehicule": {
"$ref": "9"
}
},
{
"$ref": "19"
},
{
"$ref": "20"
}
]
}
},
{
"$ref": "29"
},
{
"$ref": "6"
}
],
"fleetDetailFleetChildNavigation": []
},
"vehicule": {
"$ref": "1"
}
},
{
"$id": "30",
"fleetDetailId": 27476,
"fleetId": 5534,
"vehiculeId": 359586015016459,
"rowEnabled": true,
"fleet": {
"$id": "31",
"fleetId": 5534,
"companyId": 1,
"name": "Ol",
"rowEnabled": true,
"fleetDetailFleet": [
{
"$ref": "30"
}
],
"fleetDetailFleetChildNavigation": []
},
"vehicule": {
"$ref": "1"
}
}
]
}
Currently my controller method is the following:
[HttpPost]
public async Task<IActionResult> UpdateDati([FromBody] Vehicule model)
{...}
I'm surprised there is no simple way to sepcify this kind of behavior for model binding. What am I missing here?
The solution is to write a custom model binder to use JSON.Net to deserialize the request body:
/// <summary>
/// Custom model binder to be used when TrackableEntities coming in HttpPost Methods.
/// </summary>
public class TrackableEntityModelBinder : IModelBinder
{
/// <inheritdoc/>
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body))
{
var body = await reader.ReadToEndAsync().ConfigureAwait(continueOnCapturedContext: false);
// Do something
var value = JsonConvert.DeserializeObject(body, bindingContext.ModelType, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
});
bindingContext.Result = ModelBindingResult.Success(value);
}
}
}
Then, just anotate your HttpPost method parameter to use the model binder:
[HttpPost]
public async Task<IActionResult> UpdateDati([ModelBinder(typeof(TrackableEntityModelBinder))] [FromBody] Vehicule model)
{
}
Can you try removing them:
.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
does your Vehicule object match (I just used paste special in VS)
public class Rootobject
{
public string id { get; set; }
public long vehiculeId { get; set; }
public int companyId { get; set; }
public string phoneNumber { get; set; }
public long hardwareId { get; set; }
public int gpsBoxType { get; set; }
public string name { get; set; }
public int iconId { get; set; }
public int gpsBoxTrackingDelay { get; set; }
public bool rowEnabled { get; set; }
public long dbInsertTime { get; set; }
public Device device { get; set; }
public Vehiculegpsboxinfo vehiculeGpsBoxInfo { get; set; }
public Fleetdetail[] fleetDetail { get; set; }
}
public class Device
{
public string id { get; set; }
public long imei { get; set; }
public string brand { get; set; }
public string model { get; set; }
public string name { get; set; }
public Registration registration { get; set; }
}
public class Registration
{
public string id { get; set; }
public long imei { get; set; }
public int companyId { get; set; }
public long latestRegistrationStatusChangeDate { get; set; }
public int registrationStatus { get; set; }
public Imeinavigation imeiNavigation { get; set; }
}
public class Imeinavigation
{
public string _ref { get; set; }
}
public class Vehiculegpsboxinfo
{
public string id { get; set; }
public long vehiculeId { get; set; }
public int currentDelay { get; set; }
public int normalTrackingMode { get; set; }
public int timeModeDelay { get; set; }
public int smartModeDelay { get; set; }
public int smartModeDistance { get; set; }
public bool connected { get; set; }
public int heartBeatPeriod { get; set; }
public bool insureCoherence { get; set; }
public bool killHedgehog { get; set; }
public long lastCommunicationTime { get; set; }
public int vehiculeConfiguration { get; set; }
public int updateStatus { get; set; }
public Vehicule vehicule { get; set; }
public Vehiculeconfigurationnavigation vehiculeConfigurationNavigation { get; set; }
}
public class Vehicule
{
public string _ref { get; set; }
}
public class Vehiculeconfigurationnavigation
{
public string id { get; set; }
public int configurationId { get; set; }
public string configName { get; set; }
public string masterName { get; set; }
public string master { get; set; }
public string firmware { get; set; }
public string system { get; set; }
public int gpsBoxType { get; set; }
public object[] vehiculeGpsBoxInfoBoardConfigurationNavigation { get; set; }
public Vehiculegpsboxinfovehiculeconfigurationnavigation[] vehiculeGpsBoxInfoVehiculeConfigurationNavigation { get; set; }
}
public class Vehiculegpsboxinfovehiculeconfigurationnavigation
{
public string _ref { get; set; }
}
public class Fleetdetail
{
public string id { get; set; }
public int fleetDetailId { get; set; }
public int fleetId { get; set; }
public long vehiculeId { get; set; }
public bool rowEnabled { get; set; }
public Fleet fleet { get; set; }
public Vehicule7 vehicule { get; set; }
}
public class Fleet
{
public string id { get; set; }
public int fleetId { get; set; }
public int companyId { get; set; }
public string name { get; set; }
public bool rowEnabled { get; set; }
public Fleetdetailfleet[] fleetDetailFleet { get; set; }
public object[] fleetDetailFleetChildNavigation { get; set; }
}
public class Fleetdetailfleet
{
public string id { get; set; }
public int fleetDetailId { get; set; }
public int fleetId { get; set; }
public long vehiculeId { get; set; }
public bool rowEnabled { get; set; }
public Fleet1 fleet { get; set; }
public Vehicule1 vehicule { get; set; }
public string _ref { get; set; }
}
public class Fleet1
{
public string _ref { get; set; }
}
public class Vehicule1
{
public string id { get; set; }
public long vehiculeId { get; set; }
public int companyId { get; set; }
public string phoneNumber { get; set; }
public long hardwareId { get; set; }
public int gpsBoxType { get; set; }
public string category { get; set; }
public string name { get; set; }
public int iconId { get; set; }
public int gpsBoxTrackingDelay { get; set; }
public int addressProtocol { get; set; }
public bool rowEnabled { get; set; }
public long dbInsertTime { get; set; }
public Device1 device { get; set; }
public Vehiculegpsboxinfo1 vehiculeGpsBoxInfo { get; set; }
public Fleetdetail2[] fleetDetail { get; set; }
}
public class Device1
{
public string id { get; set; }
public long imei { get; set; }
public string brand { get; set; }
public string model { get; set; }
public string name { get; set; }
public Registration1 registration { get; set; }
}
public class Registration1
{
public string id { get; set; }
public long imei { get; set; }
public int companyId { get; set; }
public long latestRegistrationStatusChangeDate { get; set; }
public int registrationStatus { get; set; }
public Imeinavigation1 imeiNavigation { get; set; }
}
public class Imeinavigation1
{
public string _ref { get; set; }
}
public class Vehiculegpsboxinfo1
{
public string id { get; set; }
public long vehiculeId { get; set; }
public int currentDelay { get; set; }
public int normalTrackingMode { get; set; }
public int timeModeDelay { get; set; }
public int smartModeDelay { get; set; }
public int smartModeDistance { get; set; }
public bool connected { get; set; }
public int heartBeatPeriod { get; set; }
public bool insureCoherence { get; set; }
public bool killHedgehog { get; set; }
public bool boardConnected { get; set; }
public long lastCommunicationTime { get; set; }
public long boardLastCommunicationTime { get; set; }
public int vehiculeConfiguration { get; set; }
public int updateStatus { get; set; }
public Vehicule2 vehicule { get; set; }
public Vehiculeconfigurationnavigation1 vehiculeConfigurationNavigation { get; set; }
}
public class Vehicule2
{
public string _ref { get; set; }
}
public class Vehiculeconfigurationnavigation1
{
public string id { get; set; }
public int configurationId { get; set; }
public string configName { get; set; }
public string masterName { get; set; }
public string master { get; set; }
public string firmware { get; set; }
public string system { get; set; }
public int gpsBoxType { get; set; }
public object[] vehiculeGpsBoxInfoBoardConfigurationNavigation { get; set; }
public Vehiculegpsboxinfovehiculeconfigurationnavigation1[] vehiculeGpsBoxInfoVehiculeConfigurationNavigation { get; set; }
}
public class Vehiculegpsboxinfovehiculeconfigurationnavigation1
{
public string _ref { get; set; }
public string id { get; set; }
public long vehiculeId { get; set; }
public int currentDelay { get; set; }
public int normalTrackingMode { get; set; }
public int timeModeDelay { get; set; }
public int smartModeDelay { get; set; }
public int smartModeDistance { get; set; }
public bool connected { get; set; }
public int heartBeatPeriod { get; set; }
public bool insureCoherence { get; set; }
public bool killHedgehog { get; set; }
public long lastCommunicationTime { get; set; }
public int vehiculeConfiguration { get; set; }
public int updateStatus { get; set; }
public long lastConnexionTime { get; set; }
public Vehicule3 vehicule { get; set; }
public Vehiculeconfigurationnavigation2 vehiculeConfigurationNavigation { get; set; }
}
public class Vehicule3
{
public string id { get; set; }
public long vehiculeId { get; set; }
public int companyId { get; set; }
public string phoneNumber { get; set; }
public long hardwareId { get; set; }
public int gpsBoxType { get; set; }
public string name { get; set; }
public int iconId { get; set; }
public int gpsBoxTrackingDelay { get; set; }
public int addressProtocol { get; set; }
public bool rowEnabled { get; set; }
public long dbInsertTime { get; set; }
public Device2 device { get; set; }
public Vehiculegpsboxinfo2 vehiculeGpsBoxInfo { get; set; }
public Fleetdetail1[] fleetDetail { get; set; }
}
public class Device2
{
public string id { get; set; }
public long imei { get; set; }
public string brand { get; set; }
public string model { get; set; }
public string name { get; set; }
public Registration2 registration { get; set; }
}
public class Registration2
{
public string id { get; set; }
public long imei { get; set; }
public int companyId { get; set; }
public long latestRegistrationStatusChangeDate { get; set; }
public int registrationStatus { get; set; }
public Imeinavigation2 imeiNavigation { get; set; }
}
public class Imeinavigation2
{
public string _ref { get; set; }
}
public class Vehiculegpsboxinfo2
{
public string _ref { get; set; }
}
public class Fleetdetail1
{
public string id { get; set; }
public int fleetDetailId { get; set; }
public int fleetId { get; set; }
public long vehiculeId { get; set; }
public bool rowEnabled { get; set; }
public Fleet2 fleet { get; set; }
public Vehicule5 vehicule { get; set; }
}
public class Fleet2
{
public string id { get; set; }
public int fleetId { get; set; }
public int companyId { get; set; }
public string name { get; set; }
public bool rowEnabled { get; set; }
public Fleetdetailfleet1[] fleetDetailFleet { get; set; }
public object[] fleetDetailFleetChildNavigation { get; set; }
}
public class Fleetdetailfleet1
{
public string id { get; set; }
public int fleetDetailId { get; set; }
public int fleetId { get; set; }
public long vehiculeId { get; set; }
public bool rowEnabled { get; set; }
public Fleet3 fleet { get; set; }
public Vehicule4 vehicule { get; set; }
public string _ref { get; set; }
}
public class Fleet3
{
public string _ref { get; set; }
}
public class Vehicule4
{
public string _ref { get; set; }
}
public class Vehicule5
{
public string _ref { get; set; }
}
public class Vehiculeconfigurationnavigation2
{
public string _ref { get; set; }
}
public class Fleetdetail2
{
public string id { get; set; }
public int fleetDetailId { get; set; }
public int fleetId { get; set; }
public long vehiculeId { get; set; }
public bool rowEnabled { get; set; }
public Fleet4 fleet { get; set; }
public Vehicule6 vehicule { get; set; }
public string _ref { get; set; }
}
public class Fleet4
{
public string id { get; set; }
public int fleetId { get; set; }
public int companyId { get; set; }
public string name { get; set; }
public bool rowEnabled { get; set; }
public Fleetdetailfleet2[] fleetDetailFleet { get; set; }
public object[] fleetDetailFleetChildNavigation { get; set; }
public string _ref { get; set; }
}
public class Fleetdetailfleet2
{
public string _ref { get; set; }
}
public class Vehicule6
{
public string _ref { get; set; }
}
public class Vehicule7
{
public string _ref { get; set; }
}

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

DeSerialize Json into Class object

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

How to deserialize json with class name as dynamic values

How can I De-serialize following json?
{
"data": {
"11396": {
"description": "Timer project",
"status": "ACTIVE",
"customer": {
"locations": {},
"id": 96626
},
"tasks": [
{
"description": "Timer Task",
"unit": "h",
"vatPct": 0.2,
"unitPrice": 12,
"billable": true,
"id": 19660
}
],
"price": 0,
"pricing": "UNIT",
"allowProducts": true,
"hasUninvoicedItems": false,
"id": 11396
},
"11397": {
"description": "Timer Project 2",
"status": "ACTIVE",
"customer": {
"locations": {},
"id": 96626
},
"tasks": [
{
"description": "Timer Task2",
"unit": "h",
"vatPct": 0.05,
"unitPrice": 20,
"billable": true,
"id": 19655
}
],
"price": 0,
"pricing": "UNIT",
"allowProducts": true,
"hasUninvoicedItems": false,
"id": 11397
}
},
"ok": true
}
The problem is that values 11396, 11397 as class name (if convert to c#) which are actually ids of that particular record. so when converting this json to c# using http://json2csharp.com. it shows as this
public class Locations
{
}
public class Customer
{
public Locations locations { get; set; }
public int id { get; set; }
}
public class Task
{
public string description { get; set; }
public string unit { get; set; }
public double vatPct { get; set; }
public double unitPrice { get; set; }
public bool billable { get; set; }
public int id { get; set; }
}
public class __invalid_type__11397
{
public string description { get; set; }
public string status { get; set; }
public Customer customer { get; set; }
public List<Task> tasks { get; set; }
public double price { get; set; }
public string pricing { get; set; }
public bool allowProducts { get; set; }
public bool hasUninvoicedItems { get; set; }
public int id { get; set; }
}
public class Locations2
{
}
public class Customer2
{
public Locations2 locations { get; set; }
public int id { get; set; }
}
public class Task2
{
public string description { get; set; }
public string unit { get; set; }
public double vatPct { get; set; }
public double unitPrice { get; set; }
public bool billable { get; set; }
public int id { get; set; }
}
public class __invalid_type__11396
{
public string description { get; set; }
public string status { get; set; }
public Customer2 customer { get; set; }
public List<Task2> tasks { get; set; }
public double price { get; set; }
public string pricing { get; set; }
public bool allowProducts { get; set; }
public bool hasUninvoicedItems { get; set; }
public int id { get; set; }
}
public class Data
{
public __invalid_type__11397 __invalid_name__11397 { get; set; }
public __invalid_type__11396 __invalid_name__11396 { get; set; }
}
public class RootObject
{
public Data data { get; set; }
public bool ok { get; set; }
}
any help is much appreciated.
I resolved this issue by parsing the json string to JTOKEN and the querying the required data.
This was possible because my datas inside json was static
JToken token = JObject.Parse(response);
var justDaily = token["data"];
ProjectList = new List<Project>();
foreach (JToken child in justDaily.Children())
{
foreach (JToken grandChild in child)
{
Project temp = JsonConvert.DeserializeObject<Project>(grandChild.ToString().Replace("\r\n", ""));
ProjectList.Add(temp);
}
}
Hope this will help someone else also

Categories