Marsyas  0.5.0-beta1
/Users/jleben/code/marsyas/src/marsyas/json_io.cpp
Go to the documentation of this file.
00001 #include "json_io.h"
00002 #include <json.hh>
00003 #include <string>
00004 #include <iostream>
00005 #include <sstream>
00006 
00007 namespace Marsyas {
00008 
00009 using std::string;
00010 
00011 static MarSystem *system_from_json( const JSON::Value &json, MarSystemManager & manager )
00012 {
00013   if (json.type() != JSON::OBJECT)
00014     return 0;
00015 
00016   JSON::Object object( std::move(json) );
00017 
00018   string system_type = object["type"];
00019   string system_name = object["name"];
00020 
00021   if (system_type.empty())
00022     return 0;
00023 
00024   MarSystem *system = manager.create(system_type, system_name);
00025 
00026   if (!system)
00027     return 0;
00028 
00029   JSON::Object controls( std::move(object["controls"]) );
00030   for( auto control : controls )
00031   {
00032       const std::string & ctl_name = control.first;
00033       const JSON::Value & ctl_value = control.second;
00034       switch(ctl_value.type())
00035       {
00036       case JSON::BOOL:
00037         system->setControl(string("mrs_bool/") + ctl_name, (bool) ctl_value);
00038         break;
00039       case JSON::INT:
00040         system->setControl(string("mrs_natural/") + ctl_name, (mrs_natural) (int) ctl_value);
00041         break;
00042       case JSON::FLOAT:
00043         system->setControl(string("mrs_real/") + ctl_name, (mrs_real) ctl_value);
00044         break;
00045       case JSON::STRING:
00046         system->setControl(string("mrs_string/") + ctl_name, (mrs_string) ctl_value);
00047         break;
00048       // case JSON::OBJECT:
00049         // TODO: link controls
00050       default:
00051         throw std::runtime_error("Unsupported control value type.");
00052       }
00053   }
00054   system->update();
00055 
00056   JSON::Array children( std::move(object["children"]) );
00057   int i = 0;
00058   for( auto value : children )
00059   {
00060     ++i;
00061     MarSystem *child = system_from_json(value, manager);
00062     if (child)
00063     {
00064       if (child->getName().empty())
00065       {
00066         std::ostringstream name;
00067         name << "_" << i << "_";
00068         child->setName(name.str());
00069       }
00070       system->addMarSystem(child);
00071     }
00072   }
00073 
00074   return system;
00075 }
00076 
00077 MarSystem *system_from_json_string( const std::string & json_string )
00078 {
00079   MarSystemManager manager;
00080   JSON::Value data = parse_string(json_string.c_str());
00081   return system_from_json(data, manager);
00082 }
00083 
00084 MarSystem *system_from_json_file( const std::string & json_file_name )
00085 {
00086   MarSystemManager manager;
00087   JSON::Value data = parse_file(json_file_name.c_str());
00088   return system_from_json(data, manager);
00089 }
00090 
00091 }