I do wish there was a more elegant way to deal with var and json parsing in JUCE. Been doing a lot of javascript / ES6 recently and coming to do the JUCE side of things feels quite abrasive in comparison!
Ok, some var class futures are not documended in the class documentation, but, I must had a look in the var class code before I put my question here.
I tested the above expressions, based on my suspicion because of the name of the class, and after that I had a closer look on var's code.
Anyway, I feel that Jules dislikes a little bit to what is not xml, but I'm sure that it will be better because many times out there, data exchanged in this JSON way.
Sorry if my above post seemed negative. I really do appreciate the var and DynamicObject classes I just find using them a little convoluted in some cases.
For instance, if I want to add a property to a var, I initially expected to be able to just do something like:
myVar["prop"] = String("blah");
But instead I have to get the DynamicObject from the var, then its NamedValueSet, then set the property... I guess thats just how the class is structured.
I wrote a helper method which might be useful to someone:
/** Function to simplify adding properties with / to vars
*/
var propertyAsVar(const String& name, const String &value, var varToAddTo = var())
{
DynamicObject* obj = nullptr;
if (varToAddTo.isVoid())
obj = new DynamicObject();
else
obj = varToAddTo.getDynamicObject();
NamedValueSet& properties = obj->getProperties();
properties.set (name, value);
return var (obj);
}
I wonder if a method like that could be added to the [] operator of the var class?
BTW Jules how do you get your code snippets syntax highlighted like that?
You write your code into the post, then select it, and then at the top left in the "Styles" menu (the one which says "Paragraph" initially) you scroll all the way down and select the style "code: highlighted".
I tumbled on the same question for conveniently exchanging structured messages between Action Broadcasters and Listener in my App. After reviewing StringPairArray and PropertySet that lacked simple serialize/deserialize facilities, the juce::var <-> JSON synergy was most promising but how to set a property on a juce::var? thank you for your tip! coding a structured Action message becomes:
// sending side (readability can be improved with a bunch of #define's)
var v{ new DynamicObject() };
v.getDynamicObject()->setProperty(Identifier("HELLO"), var("world"));
v.getDynamicObject()->setProperty(Identifier("FOO"), var(1234));
v.getDynamicObject()->setProperty(Identifier("BAR"), var(juce::String(L"âéïôù")));
sendActionMessage(JSON::toString(v, true));
// receiver side, inside the actionListenerCallback(const String& message)
var v = JSON::fromString(message);
String s = v["HELLO"]; // by magic of operators on var
int i = v["FOO"];