JSON API
A simple API for reading/writing JSON data using C++11. No runtime dependencies other than C++11. The standard JSON value types are represented as the appropriate instances of Value. Value instance are non-copyable and hence the API cannot be packaged as a Windows DLL. On Windows, we include the sources directly into the target project.
Reading
Reading JSON data is accomplished using the convenience read or fromFile functions defined in the spt::json::io namespace. These functions conveniently wrap the implementations in the Reader class hierarchy. Reader functions return an instance of Value::Ptr which will need to be extracted into either an Object or Array instance.
#include <spt/json/Object.h> #include <spt/json/Array.h> #include <spt/json/io/Reader.h> using spt::json::Array; using spt::json::Object; using spt::json::Value; std::istream istream; // initialised to some valid stream Value::Ptr ptr = spt::json::io::read( istream ); if ( ptr->getType() == Value::Type::Object ) { const Object* obj = static_cast<const Object*>( ptr.get() ); double dval = obj->getValue<double>( "doubleValue" ); const std::string& str = obj->get<std::string>( "stringValue" ); bool bval = obj->getValue<bool>( "boolValue" ); } else if ( ptr->getType() == Value::Type::Array ) { const Array* arr = static_cast<const Array*>( ptr.get() ); double dval = arr->getValue<double>( 0 ); const std::string& str = arr->get<std::string>( 1 ); bool bval = arr->getValue<bool>( 2 ); }
Writing
Writing JSON object model (intances of Object or Array) is accomplished through the toFile functions in the spt::json::io namespace or using the Json::toJson function. All output implementations use the Writer class hierarchy for producing the output.
#include <spt/json/Object.h> #include <spt/json/Array.h> #include <spt/json/String.h> #include <spt/json/Number.h> using spt::json::Array; using spt::json::Object; using spt::json::Value; using spt::json::String; using spt::json::Number; Object object; object += Object::Pair( "one", Value::Ptr( new String( "one" ) ) ); object += Object::Pair( "two", Value::Ptr( new Number( static_cast<int64_t>( 2 ) ) ) ); std::ostream ostream; // initialised to some valid stream object.toJson( ostream, false ); Array arr; arr += Value::Ptr( new String( "one" ) ); arr += Value::Ptr( new Number( 4.4 ) ); object.toJson( ostream, true );
The JSON API is used internally by all projects that require JSON support.