Domanda

I'm using C++Builder with SuperObject JSON parser, and trying to construct an array.

_di_ISuperObject json = SO("{}");
json->O["data.names"] = SA(ARRAYOFCONST(("")));

for (int i=0; i < v.size(); ++i)
  json->A["data.names"]->S[i] = v[i];

Now, the code above does what I want - unless v.size() == 0. In that case, I get an array with a single 'empty' string in it.

This is because of the 'dummy' array creation using ARRAYOFCONST(("")).

What's the correct way to create an 'empty' OPENARRAY to pass to SuperObject?

È stato utile?

Soluzione

You cannot use ARRAYOFCONST() or OPENARRAY() to create a 0-element openarray. Those macros require a minimum of 1 input value.

I am not familiar with SuperObject, but if O[] creates a new JSON array from existing values and A[] simply fills the array, you could try using the SLICE() macro to create and fill an openarray from v directly if v is a std::vector<TVarRec>:

if (!v.empty())
    json->O["data.names"] = SA( SLICE(&v[0], v.size()) );

If you really need a 0-element openarray if v is empty, try this:

if (v.empty())
    json->O["data.names"] = SA( NULL, -1 );
else
    json->O["data.names"] = SA( SLICE(&v[0], v.size()) );

If v does not contain TVarRec values then you can create a separate std::vector<TVarRec> first and then SLICE() that into SuperObject (just be careful because TVarRec does not perform reference counting on reference-counted data types, such as strings - by design - so make sure temporaries are not created when you assign the TVarRec values or else they will be leaked!):

if (v.empty())
    json->O["data.names"] = SA( NULL, -1 );
else
{
    std:vector<TVarRec> tmp(v.size());
    for (size_t idx = 0; idx < v.size(); ++idx)
        tmp[idx] = v[idx];
    json->O["data.names"] = SA( SLICE(&tmp[0], tmp.size()) );
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top