Serialising Data to JSON or XML in Lumberyard

Just a short one this week, as we’re super busy on our next milestone. Here’s a quick and easy way to serialise your data to disc, and later retrieve it, using Amazon Lumberyard.

I’ll add a great big caveat that this is using old CryEngine systems and is therefore highly likely to be deprecated in the future. If anyone can advise on how to achieve this using newer systems, please leave a comment.

The code is pretty self-explanatory, so here it is:

#include <AzCore/IO/SystemFile.h>
#include <Serialization/IArchiveHost.h>

void SerialisationTest()
{
    struct MyData
    {
        string testVar;

        void Serialize(Serialization::IArchive& ar)
        {
            ar(testVar, "testVar", "testVar");
        }
    };

    // Create a test structure to save
    MyData data;
    data.testVar = "Test";

    // Save it to both JSON and XML
    AZ::IO::FileIOBase * io = AZ::IO::FileIOBase::GetInstance();
    char jsonPath[AZ_MAX_PATH_LEN];
    char xmlPath[AZ_MAX_PATH_LEN];
    io->ResolvePath("test.json", jsonPath, AZ_ARRAY_SIZE(jsonPath));
    io->ResolvePath("test.xml", xmlPath, AZ_ARRAY_SIZE(xmlPath));
    Serialization::SaveJsonFile(jsonPath, data);
    Serialization::SaveXmlFile(xmlPath, data, "Data");

    // Load it back in
    MyData dataJSON;
    MyData dataXML;
    Serialization::LoadJsonFile(dataJSON, jsonPath);
    Serialization::LoadXmlFile(dataXML, xmlPath);
}

The resultant output files are like so:

test.json:

{ "testVar": "Test" }

test.xml:

<Data>
 <testVar value="Test"/>
</Data>

With this, you can easily serialise strings, vectors, lists, maps, and pod types to a human-readable form.

That’s all for this week!

2 thoughts on “Serialising Data to JSON or XML in Lumberyard

Leave a Reply