Skip to main content

Notifications

Constructing JSON String using X++ code in D365FO

Hi,

While integrating with other environments the most common mode of data export is in the form of JSON string. In this post we will see how to construct JSON string from customer data.

Note: CG_BuildJSON is a runnable class.

class CG_BuildJSON
{       
    /// <summary>
    /// Construct JSON String.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {       
        System.IO.StringWriter          stringWriter;
        Newtonsoft.Json.JsonTextWriter  jsonWriter;
        CustTable                       custTable;
 
        stringWriter       = new System.IO.StringWriter();
        jsonWriter         = new Newtonsoft.Json.JsonTextWriter(stringWriter);
 
        select AccountNum, BankAccount, Party
            from custTable
            where custTable.AccountNum == "1000";
 
        str sJSON = "";
        jsonWriter.WriteStartObject();
        jsonWriter.WritePropertyName("AccountNum");
        jsonWriter.WriteValue(custTable.AccountNum);
        jsonWriter.WritePropertyName("Name");
        jsonWriter.WriteValue(custTable.nameAlias());
        jsonWriter.WritePropertyName("BankAccount");
        jsonWriter.WriteValue(custTable.BankAccount);
        jsonWriter.WriteEndObject();
 
        sJSON = stringWriter.ToString();
        Info(strFmt("%1", stringWriter.ToString()));
    }
 
}

Output

Regards,

Chaitanya Golla

Comments

*This post is locked for comments

  • Reliable Profile Picture Reliable 2,015
    Posted at
    jsonWriter.WriteStartArray(); worked. It created a separate node as expected. Thanks!
  • Reliable Profile Picture Reliable 2,015
    Posted at
    Hi Chaitanya, I am creating JSON using X++. I found your code helpful. Whereas I am trying to create inner node in JSON but couldn't get much yet, can you guide on how do I add inner node(delivery address in below case for example) in JSON, that will be very helpful. I am trying more on this. {​​​​​​​     "client": "ABC",     "region": "US",     "deliveryAddress": {​​​​​​​         "firstName": "Curtis",         "lastName": "Hughes",         "line1": "Grassmere Lane"     }​​​​​​​, "deliveryContactPhone": "8124590637", }