Tuesday, 3 January 2023

X++ code to create a JSON string

 

Sometimes we get requirement where we may need to create a JSON file. Below code generates a JSON string that can be used as an input for our requirement. We are using customer data to create this.

WriteEndArray() method help us create inner node in JSON file.


class createJSON
{      
    /// <summary>
    /// Construct a 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;
        DirPartyTable                   partyTable;
 
        stringWriter       = new System.IO.StringWriter();
        jsonWriter         = new Newtonsoft.Json.JsonTextWriter(stringWriter);
 
        select AccountNum,CustGroup,BankAccount  from custTable
        join Name, NameAlias from partyTable where partyTable.RecId == custTable.Party &&
        custTable.AccountNum == "90101";
 
        str jsonString = "";
        jsonWriter.WriteStartObject();
 
        jsonWriter.WritePropertyName("CustNum");
        jsonWriter.WriteValue(custTable.AccountNum);
 
        jsonWriter.WritePropertyName("CustGroup");
        jsonWriter.WriteValue(custTable.CustGroup);
 
        jsonWriter.WritePropertyName("BankAccount");
        jsonWriter.WriteValue(custTable.BankAccount);
 
        //Personal details start
        jsonWriter.WritePropertyName("PersonalDetails");
        jsonWriter.WriteStartArray();
        jsonWriter.WriteStartObject();
        jsonWriter.WritePropertyName("Name");
        jsonWriter.WriteValue(partyTable.Name);
 
        jsonWriter.WritePropertyName("NameAlias");
        jsonWriter.WriteValue(partyTable.NameAlias);
        jsonWriter.WriteEndObject();
        jsonWriter.WriteEndArray();
        //Personal details end
 
        jsonWriter.WriteEndObject();
 
        jsonString = stringWriter.ToString();
        Info(strFmt("%1", stringWriter.ToString()));
    }
}

No comments:

Post a Comment

Filtering Company-Specific Product Templates - SysRecordTmpTemplate lookup

Hi Techies - Recently I have come across a requirement where I needed to display product templates specific to a selected company for a give...