web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

How to get the JSON string from a custom web service ?

(0) ShareShare
ReportReport
Posted on by 395
Hi,
 
Newbie in API custom webservice thing. I created my custom web service, contain these classes : 
1. class TestAPIRequest, contain the data contract attribute
2. class TestAPIResponse, contain response message and success or not
3. class TestAPIService, contain the logic based on the request and return the response.
 
As per my understanding, in normal case will be something like this (for illustration only) :
 
 
1. class TestAPIRequest          
[DataContractAttribute]class TestAPIRequest{          private str     dataAreaId;          private str     journalNum;          [DataMember(/DataAreaId/)]          public str parmDataAreaId(str _value = dataAreaId)          {                  if (!prmIsDefault(_value))                  {                         dataAreaId = _value;                  }        return dataAreaId;          }          [DataMember(/JournalNumber/)]          public str parmJournalNumber(str _value = journalNumber)          {                   if (!prmIsDefault(_value))                   {                          journalNumber= _value;                   }        return journalNumber;           }}
 
2. class TestAPIResponse
[DataContractAttribute]class TestAPIResponse{          private boolean success;          private str     message;           [DataMember(/Success/)]          public boolean parmSuccess(boolean _value = success)          {                  if (!prmIsDefault(_value))                  {                         success = _value;                  }                  return success;           }    [DataMember(/Message/)]           public str parmMessage(str _value = message)          {                   if (!prmIsDefault(_value))                   {                          message = _value;                   }                   return message;            }}
 
 
3. class TestAPIService
public class TestAPIService{    public TestAPIResponse postJournal(TestAPIRequest  _request)    {       try {                    var response = new TestAPIResponse();            changecompany(_request.parmDataAreaId())            {                 .... code....            }            response.parmMessage(/Posted/);            response.parmSuccess(true);       }       catch {              response.parmMessage(/Error/);              response.parmSuccess(false);       }       return response;     }}
Then I've created the ServiceGroup, Services which then available to be called from Postman. In Postman, basically I will put JSON string in the Body, something like:
{    /_request/: {                /DataAreaId/: /TEST/,                /JournalNumber/ : /JN000730/           }}
Question is: if I want to retrieve the request JSON string, when the service class is called, how am I gonna do that ? The intention is I want to keep the JSON string as a string in one of my table for history.
May I have a guide here. What need to be done ? how ? and where to put ?
 
Thanks
 
 
I have the same question (0)
  • Teevo Profile Picture
    395 on at
    Hi everyone,
     
    I found this interesting blog : https://community.dynamics.com/blogs/post/?postid=9f84843e-3a3e-49b0-893f-91abdcd57e42, talking about "Taking JSON input with D365 service and deserialize into contract objects"
     
    In that blog, only contain 2 classes and 1 class which is looks like a runnable class to test, which I tried to re-create:
    /// <summary>
    /// The Student Information object contains the Student ID and Name
    /// </summary>
    [DataContractAttribute]
    class Test_DataContract
    {
        str studentId;
        str studentName;
    
        [DataMemberAttribute("Student Id")]
        public str parmStudentId(str _studentId = studentId)
        {
            studentId = _studentId;
    
            return studentId;
        }
    
        [DataMemberAttribute("Student Name")]
        public str parmStudentName(str _studentName = studentName)
        {
            studentName = _studentName;
    
            return studentName;
        }
    
    }
     
    /// <summary>
    /// Contains a list of students
    /// </summary>
    [DataContractAttribute]
    class Test_StudentsContract
    {
        List studentList = new List(Types::String);
    
        [
            DataMemberAttribute("Student list"),
            DataCollectionAttribute(Types::Class, classStr(Test_DataContract))
        ]
        public List parmStudentList(List _studentList = studentList)
        {
            if (!prmIsDefault(_studentList))
            {
                studentList = _studentList;
            }
    
            return studentList;
        }
    
    }
    
     
    And the runnable class :
    internal final class Test_Students
    {
        /// <summary>
        /// Class entry point. The system will call this method when a designated menu 
        /// is selected or when execution starts and this class is set as the startup class.
        /// </summary>
        /// <param name = "_args">The specified arguments.</param>
        public static void main(Args _args)
        {
            Test_StudentsContract Test_StudentsContract = new Test_StudentsContract();
            List studentList = Test_StudentsContract.parmStudentList();
    
            ListEnumerator enumerator = studentList.getEnumerator();
    
            Test_DataContract studentInfoContract = new Test_DataContract();
    
            while (enumerator.moveNext())
            {
                Newtonsoft.Json.Linq.JObject    jObj = enumerator.current();
    
                studentInfoContract = FormJsonSerializer::deserializeObject(classNum(Test_DataContract),jObj.ToString());
    
                str studentId, studentName;
    
                studentId   = studentInfoContract.parmStudentId();
                studentName = studentInfoContract.parmStudentName();
    
                Info(strFmt("Student # %1: %2", studentId, studentName));
            }
    
    
        }
    
    }
     
    It looks fine since I build and no error. But I'm not I understand how to test it. How to test the JSON input then ?
    Because if I just "blindly" run the runnable class, the studentList obviously empty and will only exit the while loop. May I know what is the correct way to test this process.
     
    Thanks.
     
     
     
  • Suggested answer
    Martin Dráb Profile Picture
    237,878 Most Valuable Professional on at
    The JSON from the request isn't available to TestAPIService class. The deserialization from JSON was already managed by F&O kernel and what you get is instance of TestAPIRequest class with the data. You could serialize it to JSON, but it's not the same thing as logging the original request.
     
    Also, putting such logs to F&O transactional database doesn't sound like a good idea, because you'd waste database storage with data that don't really belong there.
     
    I recommend using Azure API Management (or something similar) between F&O and the other systems. Then you can easily enable logging to Application Insights there.
  • Teevo Profile Picture
    395 on at
    Hi Martin,
     
    Ok, I will take note on your advice about this is not a good idea. But is it possible though ? And how to achieve that if it is for additional knowledge ? 
    Thank you.
  • Suggested answer
    Layan Jwei Profile Picture
    8,112 Super User 2025 Season 2 on at
    Hi Teevo,

    In general, here's how you can get a JSON out of your request contract:
     
    class classTest = new classTest();
    str jsonString = FormJsonSerializer::serializeClass(classTest);

    Thanks,
    Layan Jweihan
    Please mark this answer as "Verified" if it solved your issue. In order to help others who will face a similar issue in the future. You can do this by ticking the box "Does this answer your question"
  • Teevo Profile Picture
    395 on at
    Hi Layan,
     
    But what object is this classTest() ? should I put my Request class ?
     
    Since if I take a look at the method, it is also just mentioned that it receive object. Not sure what kind of object.
     
     public static str serializeClass(Object _object)
        {
            FormJsonSerializer serializer;
    
            if (_object == null)
            {
                return 'null';
            }
    
            serializer = new FormJsonSerializer();
            serializer.serializeObject(_object);
    
            return serializer.json();
        }
     
    Can you help to applied it into my example so I can understand more on this.
    Thanks.
     
     
     
  • Verified answer
    Layan Jwei Profile Picture
    8,112 Super User 2025 Season 2 on at
    Hi Teevo,

    Yes your request class, i just called it classTest. 

    So in your case, if you will put the code inside TestAPIService, you will use this:
     str jsonString = FormJsonSerializer::serializeClass(_request);  -- let us know if it works :)

    please don't forget to verify answers that helped you to help others, I can see you have previous questions that you didn't close like this one:

    https://community.dynamics.com/forums/thread/details/?threadid=4cd9d55a-e499-ee11-be37-000d3a4fe8f7
    So please go through them

    Thanks,
    Layan Jweihan
    Please mark this answer as "Verified" if it solved your issue. In order to help others who will face a similar issue in the future. You can do this by ticking the box "Does this answer your question"
  • Martin Dráb Profile Picture
    237,878 Most Valuable Professional on at
    I believe I already answered the question whether it's possible. Logging the original request in your service class isn't possible, serializing the object back to JSON is possible.
  • Teevo Profile Picture
    395 on at
    Hi Layan,
     
    Seems work. May I know one thing, though. It's a bit not related, but yes if we saw it from testing POV. How to test this without Postman ? I mean I don't have the configuration such as my TenantID, etc, so can I run my Service class from URL, with addition of the JSON string ?
    Because currently I'm testing it from Runnable class, and in that runnable class is by passing the parameter one by one according to the contract class, then in that runnable class call my service class. It is not from a real JSON String.
     
    Sorry about the previous thread. I haven't continue it yet, and have to jump to other more urgent like this one. 
     
    Thanks.
     
  • Layan Jwei Profile Picture
    8,112 Super User 2025 Season 2 on at
    Hi Teevo,

    If your question is answered then please mark all answers that helped.

    I'm not sure I got your question correctly. but if you want to test it using runnable class by passing the json string instead of filling the contract class, then a workaround can be that you define the json string, then deserialize it back to contract, then pass it to the custom service.

    I mean:
    str json =  {"_request":{"DataAreaId":"Test}}
    TestAPIRequest apiRequest = FormJsonSerializer::deserializeObject(classNum(TestAPIRequest), json);

    If you have further questions, then it's better to create a new question

    Thanks,
    Layan Jweihan
    Please mark this answer as "Verified" if it solved your issue. In order to help others who will face a similar issue in the future. You can do this by ticking the box "Does this answer your question"
  • Teevo Profile Picture
    395 on at
    Hi Layan,
     
    Seems I cannot mark it, it always freeze, just keep processing without end. Can you help to mark it ?
    Thanks.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 646 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 529 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 285 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans