AXForum  
Вернуться   AXForum > Microsoft Dynamics AX > DAX Blogs
DAX
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 08.09.2017, 11:11   #1  
Blog bot is offline
Blog bot
Участник
 
25,475 / 846 (79) +++++++
Регистрация: 28.10.2006
gideonvos: JSON to X++ Classes the easy way
Источник: https://gideonvos.wordpress.com/2017...-the-easy-way/
==============

Calling API’s that expect and return JSON from within X++ has become fairly routine and simple with the release of Dynamics 365 for Operations. Recently we moved a module written in C# that resided as external DLL’s within AX, to an Azure-based API that talks JSON via REST. Calling the API was fairly straightforward but manipulating the JSON between X++ and the API seemed like a lot of manual work requiring get/set operations for each property.

Assume you have a class in X++ containing a number of properties, similar to this one below.

class PFLPayrollResultsRequest { str customerID; str appKey; str legalEntity; str payRunNumber; public str CustomerID(str _customerID = customerID) { customerID = _customerID; return customerID; } public str AppKey(str _appKey = appKey) { appKey = _appKey; return appKey; } public str LegalEntity(str _legalEntity = legalEntity) { legalEntity = _legalEntity; return legalEntity; } public str PayRunNumber(str _payRunNumber = payRunNumber) { payRunNumber = _payRunNumber; return payRunNumber; } }


This class might be used for data retrieval and storage within X++, and let’s assume at some point we want to send the state to an external API using JSON. At first glance it seems that we would have to access each individual property and retrieve it from the class, build the JSON string up from that, and then submit that across the wire. The NewtonSoft library gives us a fair bit of methods to work with, however that is external to X++, and NewtonSoft does not understand X++ classes. When the API call returns, it might contain thousands of records which then have to be loaded into X++ classes, property by property.

The solution lies in using the FormJsonSerializer class. Simply decorate your X++ class with a number of attributes (DataContractAttribute, DataMemberAttribute) as shown below:

[DataContractAttribute] class PFLPayrollResultsRequest { str customerID; str appKey; str legalEntity; str payRunNumber; [DataMemberAttribute] public str CustomerID(str _customerID = customerID) { customerID = _customerID; return customerID; } [DataMemberAttribute] public str AppKey(str _appKey = appKey) { appKey = _appKey; return appKey; } [DataMemberAttribute] public str LegalEntity(str _legalEntity = legalEntity) { legalEntity = _legalEntity; return legalEntity; } [DataMemberAttribute] public str PayRunNumber(str _payRunNumber = payRunNumber) { payRunNumber = _payRunNumber; return payRunNumber; } }


Now we can serialize this class to a JSON string for transfer, and also load an X++ class with the JSON result set returned. A quick example is shown below, in X++.

public static void GetTempTrans() { System.Net.WebClient webClient; System.Text.UTF8Encoding encoder; try { PFLPayrollResultsRequest request = new PFLPayrollResultsRequest(); - this is the request class we convert to JSON and send to the API request.AppKey("232B8D90-7C3BF92DEA9F"); request.CustomerID("27C2C06F8C2737"); request.LegalEntity("AUP"); request.PayRunNumber("12345"); webClient = new System.Net.WebClient(); System.Net.WebHeaderCollection headers = webClient.Headers; headers.Add("Content-Type", "application/json"); encoder = new System.Text.UTF8Encoding(); str json = FormJsonSerializer::serializeClass(request);// use this AX helper class (FormJsonSerializer) to convert to JSON here System.Byte[] encodedBytes = encoder.GetBytes(json); System.Byte[] response = webClient.UploadData("https://www.myapi.com/api/Engine/Post/TemporaryResults", encodedBytes); str jsonResponse = webClient.Encoding.GetString(response); // deserialize result returned from API here using FormJsonSerializer::deserializeClass(); } catch { } }



Источник: https://gideonvos.wordpress.com/2017...-the-easy-way/
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
Как выполнять дефрагментирование RecID mazzy DAX: База знаний и проекты 174 05.10.2017 12:59
goshoom: JSON-based custom service with parameters (AX 7) Blog bot DAX Blogs 0 23.02.2017 14:13
Navigate Into Success: Passing JSON from JavaScript to C/AL Blog bot Dynamics CRM: Blogs 0 31.12.2014 10:00
emeadaxsupport: SEPA affected objects Blog bot DAX Blogs 0 29.11.2013 13:11
Передача функции в качестве параметра lemchey_white DAX: Программирование 20 21.01.2008 22:51

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 05:34.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.