ValueTree: Loading Array<var> doesnt contain data for some reason

I have some trouble saving an Array (containing a list of int’s) and then loading it again. The loaded array contains 0 elements for some weird reason. What am I doing wrong here?

std::vector<int> myData;    // Contains data I want to save

// ...later I do the following:

jassert(myData.size() >= 2);

juce::Array<var> outputData;
outputData.resize((int) myData.size());

for (int i = 0; i < myData.size(); ++i)
    outputData.getReference(i) = myData[i];

juce::ValueTree node(MyIDs::type);
node.setProperty(MyIDs::this_and_that, outputData, nullptr);


// ...elsewhere I load the above data:
jassert(node.hasProperty(MyIDs::this_and_that));

juce::Array<var> inputData = node[MyIDs::this_and_that];

jassert(inputData.size() >= 2);

// Assertion failed: the list size is 0!

If you try to write to XML and you run under the debugger, you should get prompted here:

XML cannot store an array…

I save the file like this:

            juce::ValueTree save_state = node;
            
            juce::File file(save_file);
            file.deleteFile();

            juce::FileOutputStream outstream(file);
            save_state.writeToStream(outstream);

So that shouldn’t be XML.

Yes, with that additional information it is not the limitation of XML.

The binary representation should be able to write and restore the array.

I avoid setSize and getReference, since there are some inconsistencies (especially the operator[]).

Instead I would try:

juce::var arr;
for (auto v : myData)
    arr.append (v);

jassert (arr.isArray());
jassert (arr.size() == myData.size());

Especially I wouldn’t trust:

juce::Array<var> inputData = node[MyIDs::this_and_that];

Instead I’d try:

auto arr = inputData.getProperty (MyIDs::this_and_that);
jassert (arr.isArray());
jassert (arr.size() >= 2);

But it is just guessing, haven’t tried your code.

1 Like

Aha! Now it seems to work when I used the following lines from your example:

Great, glad it works. I just banged it in for reference:

:slight_smile:

Maybe something when copying the juce::Array into the property failed…
Better to have it as var in the first place

1 Like