Tuesday, January 17, 2023

Deserialize JSON file using Json Object In D365FO.

Deserialize JSON file using Json Object clss in D365FO.

Sample File :

{
    "Contract" : 
    {
	"CustomerId" : "123",
	"Name" 		 : "Test 123",
	"SalesOrders" : [
	{
	    "salesOrder" : "S123",
	    "SequenceNumber" : "S123456",
	    "SalesLines" : [
		{
		    "item"  : "Item123",
		    "qty"   : "1",
		    "price" : "33.01"
		},
		{
		    "item"  : "Item456",
		    "qty"   : "2",
		    "price" : "30.01"
		}
		]
	}
	],
	"Address" :
	{
	    "City" 	    : "Hyd",
	    "AddressLine"   : "KK"
	}
    }
}


Code :

if (jsonString)
{
	str  customerId, name;
	str  salesOrder;
	str  item, qty, price;

	Newtonsoft.Json.Linq.JObject  contractData    = Newtonsoft.Json.JsonConvert::DeserializeObject(jsonString);// main Json file
	Newtonsoft.Json.Linq.JObject  contractDataObj = contractData.GetValue('Contract');// 1st node

	customerId	= contractDataObj.GetValue('CustomerId') ? contractDataObj.GetValue('CustomerId').ToString() : '';//string value
	name		= contractDataObj.GetValue('Name') ? contractDataObj.GetValue('Name').ToString() : '';

	//Array
	Newtonsoft.Json.Linq.JArray  salesOrderArray = ComponentDataObj.GetValue('SalesOrders');
	
	for (int i = 0; i < salesOrderArray.Count; i++)
	{
		Newtonsoft.Json.Linq.JObject    salesOrderObj = salesOrderArray.get_item(i);//line by line

		salesOrder	   = salesOrderObj.GetValue('salesOrder') ? salesOrderObj.GetValue('salesOrder').ToString() : '';//string value
		SequenceNumber = salesOrderObj.GetValue('SequenceNumber') ? salesOrderObj.GetValue('SequenceNumber').ToString() : '';

		info (strFmt('salesOrder - %1,SequenceNumber -%2', salesOrder, SequenceNumber));

		// Array
		Newtonsoft.Json.Linq.JArray  salesLinesArray = assetInfoObj.GetValue('SalesLines');
		for (int j = 0; j < salesLinesArray.Count; j++)
		{
			Newtonsoft.Json.Linq.JObject    salesLinesObj = salesLinesArray.get_item(j);

			item = salesLinesObj.GetValue('item') ? salesLinesObj.GetValue('item').ToString() : '';
			qty = salesLinesObj.GetValue('qty') ? salesLinesObj.GetValue('qty').ToString() : '';
			price = salesLinesObj.GetValue('price') ? salesLinesObj.GetValue('price').ToString() : '';

			info (strFmt('item - %1',item));
		}	
	}		

		// Address - Node
		Newtonsoft.Json.Linq.JObject  addressObj = assetInfoObj.GetValue('Address');

		addressLine = addressObj.GetValue('AddressLine') ? addressObj.GetValue('AddressLine').ToString() : '';
		city        = addressObj.GetValue('City') ? addressObj.GetValue('City').ToString() : '';

		info (strFmt('City - %1,AddressLine -%2',city,addressLine));
}



Keep Daxing!!

No comments:

Post a Comment