Serialize and Deserialize JSON in X++

JSON strings can easily be handled using the FormJSONSerialized class in Dynamics 365 FO. Here is an example:

// JSON with string and number
str jsonString = @'{"Name":"Dynamics 365","RefRecId":123456789}';

Data Contract

Create an X++ class that matchtes the properties and add the DataContract and DataMember attributes. The attribute name has to match the JSON property name. You can stick to the parm*() naming schema for the method.

[DataContract]
class ERPDataContract
{
    Name name;
    RefRecId refRecId;

    [DataMember("Name")]
    public Name parmName(Name _name = name)
    {
        name = _name;
        return name;
    }

    [DataMember("RefRecId")]
    public RefRecId parmRefRecId(RefRecId _refRecId = RefRecId)
    {
        refRecId = _refRecId;
        return refRecId;
    }
}

Deserialize from JSON to X++ object

ERPDataContract xppObject = FormJsonSerializer::deserializeObject(
                                                        classNum(ERPDataContract),
                                                        jsonString);

info(strfmt("Name = %1, RefRecId = %2",xppObject.parmName(), 
                                       xppObject.parmRefRecId()));
JSON to X++ object

Serialize X++ object to JSON string

xppObject.parmRefRecId(1010101010);
jsonString = FormJsonSerializer::serializeClass(xppObject);
info(jsonString);
X++ object to JSON