Valid JSON Unable to Return Dynamic Object


#1

Hey… This may be crazy but does something look wrong with this?

    //tried both var & string
    var jsonString = input->readEntireStreamAsString();
    var parsedJson = JSON::parse(jsonString);
    //this prints the formatted json fine
    DBG(JSON::toString(parsedJson));
    //this keeps return nullptr
    if(DynamicObject* obj = parsedJson.getDynamicObject()) {
        //never makes it here
        DBG(obj->getProperties().size());
    }

is it plausible I’m just losing my mind?


#2

It’s perfectly plausible if the var isn’t actually an object. Your code doesn’t tell us anything without the string is that you’re feeding into it!


#3

flag for delete


#4

Stepping through I see first this get called in the juce_Variant.cpp:

DynamicObject* var::getDynamicObject() const noexcept { return dynamic_cast<DynamicObject*> (getObject()); }

which goes to:

ReferenceCountedObject* var::getObject() const noexcept { return type->toObject (value); }

to…:

ReferenceCountedObject* toObject (const ValueUnion&) const noexcept override { return nullptr; }


#5

Alright I loaded some JSON from a different place and it was working fine. The issue was that before the opening JSON brace there was a bracket.

so it was:
[{
JSON
}]

That was coming back from a Web API… I’m not sure how common it is to get JSON like that, but now we know : ) maybe this will help someone else


#6

I think this is similar to a post we recently had: JUCE’s Javascript is slightly different to EMCA in that arrays aren’t objects - they are just arrays. So

if(DynamicObject* obj = parsedJson.(*getArray())[0].getDynamicObject()) {

should work instead of

if(DynamicObject* obj = parsedJson.getDynamicObject()) {

as your web-service is returning a single object ({}) inside an array ([]).