Tuesday, May 10, 2022

How to Serialize JSON file in d365FO

Hi guys, Today we see how to Serialize JSON files in d365FO.

For this, I am using the contract class.


Contract class:

[DataContractAttribute]
public class MyTestContract
{
    str     id;
    Name    name;


    [DataMemberAttribute('id')]
    public str parmId(str _id = id)
    {
        id = _id;

        return id;
    }

    [DataMemberAttribute('Name')]
    public str parmName(Name _name = name)
    {
        name = _name;

        return name;
    }

}

Main method:

For the single record:

 public static str getJson(Id  _id, Name  _name)

{
    MyTestContract    myTestContract = new MyTestContract();

    myTestContract.parmId(_id);
    myTestContract.parmName(_name);

    return FormJsonSerializer::serializeClass(myTestContract);// creates json file
}

Output:

{"id":"Test 001","Name":"Testing"}


For multiple records:

 public static void getJson()

{
    str             json;
    CustGroup       custGroup;
    List            resultSet = new List(Types::Class);

    while select custGroup
    {
        MyTestContract    myTestContract = new MyTestContract();

        myTestContract.parmId(custGroup.CustGroup);
        myTestContract.parmName(custGroup.Name);

        resultSet.addEnd(myTestContract);
    }

    json = FormJsonSerializer::serializeClass(resultSet);
 
    info(strFmt("%1", json));
}

Output:

[{"id":"Test 001","Name":"Testing1"},
{"id":"Test 002","Name":"Testing2"},
{"id":"Test 003","Name":"Testing3"},
{"id":"Test 004","Name":"Testing4"},
{"id":"Test 005","Name":"Testing5"}]
Keep daxing!!



No comments:

Post a Comment