Valijson è una libreria molto buona che dipende solo da Boost (e in realtà spero di poterlo fare a change). Non dipende nemmeno da alcun particolare parser JSON, fornendo adattatori per le librerie più comuni come JsonCpp, rapidjson e json11.
Il codice può sembrare prolisso, ma si può sempre scrivere un aiutante (esempio per JsonCpp):
#include <json-cpp/json.h>
#include <sstream>
#include <valijson/adapters/jsoncpp_adapter.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
#include <valijson/validation_results.hpp>
#include <valijson/validator.hpp>
void validate_json(Json::Value const& root, std::string const& schema_str)
{
using valijson::Schema;
using valijson::SchemaParser;
using valijson::Validator;
using valijson::ValidationResults;
using valijson::adapters::JsonCppAdapter;
Json::Value schema_js;
{
Json::Reader reader;
std::stringstream schema_stream(schema_str);
if (!reader.parse(schema_stream, schema_js, false))
throw std::runtime_error("Unable to parse the embedded schema: "
+ reader.getFormatedErrorMessages());
}
JsonCppAdapter doc(root);
JsonCppAdapter schema_doc(schema_js);
SchemaParser parser(SchemaParser::kDraft4);
Schema schema;
parser.populateSchema(schema_doc, schema);
Validator validator(schema);
validator.setStrict(false);
ValidationResults results;
if (!validator.validate(doc, &results))
{
std::stringstream err_oss;
err_oss << "Validation failed." << std::endl;
ValidationResults::Error error;
int error_num = 1;
while (results.popError(error))
{
std::string context;
std::vector<std::string>::iterator itr = error.context.begin();
for (; itr != error.context.end(); itr++)
context += *itr;
err_oss << "Error #" << error_num << std::endl
<< " context: " << context << std::endl
<< " desc: " << error.description << std::endl;
++error_num;
}
throw std::runtime_error(err_oss.str());
}
}
molto probabilmente perché C e C++ sono raramente utilizzate per webapps, che è l'applicazione predominante di JSON. Se non ce ne sono, puoi prenderne un altro e portarlo. –
JSON può (è?) Utilizzato per molto più che parlare tra browser e server web. Potresti volerlo usare per memorizzare le preferenze, RPC tra i sistemi, ecc. Fondamentalmente, ovunque xml è (errato) usato oggi. –
@ Mark: effettivamente questo è il nostro caso d'uso esatto. Abbiamo bisogno di un modo per archiviare una configurazione complessa (troppo complessa per ini). Abbiamo scelto JSON come oltre xml. –