本文整理汇总了C++中Json类的典型用法代码示例。如果您正苦于以下问题:C++ Json类的具体用法?C++ Json怎么用?C++ Json使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Json类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: id
SpaceStationType::SpaceStationType(const std::string &id_, const std::string &path_)
: id(id_)
, model(0)
, modelName("")
, angVel(0.f)
, dockMethod(SURFACE)
, numDockingPorts(0)
, numDockingStages(0)
, numUndockStages(0)
, shipLaunchStage(3)
, parkingDistance(0)
, parkingGapSize(0)
{
Json data = JsonUtils::LoadJsonDataFile(path_);
if (data.is_null()) {
Output("couldn't read station def '%s'\n", path_.c_str());
throw StationTypeLoadError();
}
modelName = data.value("model", "");
const std::string type = data.value("type", "");
if (type == "surface")
dockMethod = SURFACE;
else if (type == "orbital")
dockMethod = ORBITAL;
else {
Output("couldn't parse station def '%s': unknown type '%s'\n", path_.c_str(), type.c_str());
throw StationTypeLoadError();
}
angVel = data.value("angular_velocity", 0.0f);
parkingDistance = data.value("parking_distance", 0.0f);
parkingGapSize = data.value("parking_gap_size", 0.0f);
padOffset = data.value("pad_offset", 150.f);
model = Pi::FindModel(modelName, /* allowPlaceholder = */ false);
if (!model) {
Output("couldn't initialize station type '%s' because the corresponding model ('%s') could not be found.\n", path_.c_str(), modelName.c_str());
throw StationTypeLoadError();
}
OnSetupComplete();
}
示例2: _json_to_lua
static void _json_to_lua(lua_State *l, const Json &data)
{
LUA_DEBUG_START(l);
switch (data.type()) {
case Json::nullValue:
lua_pushnil(l);
break;
case Json::intValue:
case Json::uintValue:
case Json::realValue:
lua_pushnumber(l, data.asDouble());
break;
case Json::stringValue: {
const std::string &str(data.asString());
lua_pushlstring(l, str.c_str(), str.size());
break;
}
case Json::booleanValue:
lua_pushboolean(l, data.asBool());
break;
case Json::arrayValue: {
lua_newtable(l);
for (int i = 0; i < int(data.size()); i++) {
lua_pushinteger(l, i+1);
_json_to_lua(l, data[i]);
lua_rawset(l, -3);
}
break;
}
case Json::objectValue: {
lua_newtable(l);
for (Json::const_iterator i = data.begin(); i != data.end(); ++i) {
const std::string &key(i.key().asString());
lua_pushlstring(l, key.c_str(), key.size());
_json_to_lua(l, *i);
lua_rawset(l, -3);
}
break;
}
}
LUA_DEBUG_END(l, 1);
}
示例3: parse_login_data
/* Convert login information from string to standard json {id, name, site}.
* (original information can be different for different sites).
*/
Json
parse_login_data(const string & juser) {
/* convert string to json */
Json root = Json::load_string(juser);
/* if loginza returned an error - throw it */
if (!root.get("error_message").is_null())
throw Exc() << juser;
/* get identity field */
std::string identity = root["identity"].as_string();
if (identity == "") throw Err() << "login error";
/* default name */
std::string name = identity;
/* extract site */
std::string site = get_site(identity);
/* parse the name if possible and make correct full name */
Json nn = root["name"];
if (nn.is_object()) {
string n1 = nn["first_name"].as_string();
string n2 = nn["last_name"].as_string();
string n3 = nn["full_name"].as_string();
if (n3!="") name=n3;
else if (n1!="" && n2!="") name = n1+" "+n2;
else if (n2!="") name=n2;
else if (n1!="") name=n1;
}
/* lj has only identity */
if (site == "lj") {
size_t i1 = identity.find("http://");
size_t i2 = identity.find(".livejournal.com");
name = identity.substr(i1+7, i2-i1-7);
}
/* build the output json */
Json ret = Json::object();
ret.set("id", Json(identity));
ret.set("site", Json(site));
ret.set("name", Json(name));
return ret;
}
示例4: main
int main(int argc, char** argv) {
if (argc != 2) {
cout << "Usage: clison filename.json\n";
return 1;
}
try {
#ifdef WITH_SCHEMA
ifstream schfs("schema.json");
if (!schfs)
cout << "note: schema.json not found\n";
else {
//meta = Json(schfs);
schfs >> meta;
string schema_url = "http://json-schema.org/draft-04/schema#";
if (meta.type() != Json::OBJECT || meta["$schema"] != schema_url) {
cout << "schema.json is not a http://json-schema.org/draft-04/schema\n";
meta = Json::null;
}
schfs.close();
sprops = meta["properties"];
}
#endif
ifstream fs(argv[1]);
Json js(fs);
fs.close();
Json::indent = 2;
vector<string> path;
cli(js, js, path);
} catch (Json::use_error& ex) {
cout << "use_error: " << ex.what() << '\n';
} catch (Json::parse_error& ex) {
cout << "parse_error: " << ex.what() << '\n';
cout << "line: " << ex.line << ", col: " << ex.col << '\n';
} catch (std::exception& ex) {
cout << "exception: " << ex.what() << '\n';
}
#ifdef TEST
meta = Json::null;
schema = Json::null;
Json::test();
#endif
}
示例5: printf
Json RiotService::GetMatchFeedByIds::internalCall() {
Json summoners = _service->_api.getSummonerByIds(_params["ids"]);
Json::object diff;
Json::array matches;
std::string err;
auto cmp = [](const Json & a, const Json & b) {
return a["createDate"].number_value() > b["createDate"].number_value();
};
for (auto & kv : summoners.object_items()) {
Json cache = _service->getSummonerInfoCache(kv.first);
printf("cache : %s\nnew: %s", cache.dump().c_str(), kv.second.dump().c_str());
if (cache.is_null() || cache["revisionDate"].number_value() < kv.second["revisionDate"].number_value()) {
diff[kv.first] = kv.second;
} else {
matches.insert(matches.end(), cache["games"].array_items().begin(), cache["games"].array_items().end());
}
}
std::sort(matches.begin(), matches.end(), cmp);
if (!matches.empty()) {
_onRead(matches);
}
for (auto & kv : diff) {
auto future = std::async(std::launch::async, [this, kv, cmp, &matches]() {
Json newInfo = _service->_api.getRecentGamesBySummonerId(kv.first);
if (!newInfo.is_null()) {
Json::array modifiedMatches;
for (auto & match : newInfo["games"].array_items()) {
auto item = match.object_items();
item["summonerId"] = kv.first;
item["name"] = kv.second["name"].string_value();
modifiedMatches.push_back(item);
}
matches.insert(matches.end(), modifiedMatches.begin(), modifiedMatches.end());
sort(matches.begin(), matches.end(), cmp);
Json::object updateObject(kv.second.object_items());
updateObject["games"] = modifiedMatches;
_service->saveSummonerInfo(kv.first, Json(updateObject));
}
_onRead(matches);
});
}
return Json(matches);
}
示例6: main
int main(int argc, char *argv[])
{
try
{
Json js;
std::string str("Test\\ string\\ end\\\nAnders was here\n\"Quoted string inside string\"\n");
std::cout << " --------------- original\n";
std::cout << str << std::endl;
js.encode(str);
std::cout << " --------------- encoded\n";
std::cout << str << std::endl;
js.decode(str);
std::cout << " --------------- decoded\n";
std::cout << str << std::endl;
js["String"] = str;
str = js.ToString();
std::cout << " --------------- from ToString()\n";
std::cout << str << std::endl;
Json js2 = Json::Parse(str);
std::cout << js2.ToString() << std::endl;
std::cout << (std::string)js2["String"] << std::endl;
str = "{\"no-value\":null}";
Json js3 = Json::Parse(str);
std::cout << js3.ToString() << std::endl;
std::cout << " --------------- request\n";
Json req;
req["method"] = "test";
Json params;
params["value1"] = 1L;
params["value2"] = "2";
req["params"] = params;
std::cout << req.ToString() << std::endl;
}
catch (const Exception& e)
{
std::cerr << e.ToString() << std::endl;
}
}
示例7:
void
SqliteStore::set(const string& key, const Json& value) {
auto serialized = value.dump();
sqlite::WriteTransaction guard {m_stmts};
bool did_update = false;
{
auto& stmt = m_update;
stmt->reset();
stmt->bind(1, key);
stmt->bind(2, serialized);
did_update = stmt->exec() > 0;
}
if (!did_update) {
auto& stmt = m_insert;
stmt->reset();
stmt->bind(1, key);
stmt->bind(2, serialized);
stmt->exec();
}
guard.commit();
}
示例8: main
int main(int argc, char* argv[])
{
std::string compiler;
std::string compilerPath;
Vstring linklineA;
extract_linker(compiler, compilerPath, linklineA);
Json json;
json.add("compiler", compiler);
json.add("compilerPath", compilerPath);
json.add("link_line", linklineA);
json.fini();
std::string jsonStr = json.result();
fprintf(stdout,"%s\n",jsonStr.c_str());
return 0;
}
示例9: if
EResult<Json> Monica::findAndReplaceReferences(const Json& root, const Json& j)
{
auto sp = supportedPatterns();
//auto jstr = j.dump();
bool success = true;
vector<string> errors;
if(j.is_array() && j.array_items().size() > 0)
{
J11Array arr;
bool arrayIsReferenceFunction = false;
if(j[0].is_string())
{
auto p = sp.find(j[0].string_value());
if(p != sp.end())
{
arrayIsReferenceFunction = true;
//check for nested function invocations in the arguments
J11Array funcArr;
for(auto i : j.array_items())
{
auto r = findAndReplaceReferences(root, i);
success = success && r.success();
if(!r.success())
for(auto e : r.errors)
errors.push_back(e);
funcArr.push_back(r.result);
}
//invoke function
auto jaes = (p->second)(root, funcArr);
success = success && jaes.success();
if(!jaes.success())
for(auto e : jaes.errors)
errors.push_back(e);
//if successful try to recurse into result for functions in result
if(jaes.success())
{
auto r = findAndReplaceReferences(root, jaes.result);
success = success && r.success();
if(!r.success())
for(auto e : r.errors)
errors.push_back(e);
return{r.result, errors};
}
else
return{J11Object(), errors};
}
}
if(!arrayIsReferenceFunction)
for(auto jv : j.array_items())
{
auto r = findAndReplaceReferences(root, jv);
success = success && r.success();
if(!r.success())
for(auto e : r.errors)
errors.push_back(e);
arr.push_back(r.result);
}
return{arr, errors};
}
else if(j.is_object())
{
J11Object obj;
for(auto p : j.object_items())
{
auto r = findAndReplaceReferences(root, p.second);
success = success && r.success();
if(!r.success())
for(auto e : r.errors)
errors.push_back(e);
obj[p.first] = r.result;
}
return{obj, errors};
}
return{j, errors};
}
示例10: methodFromString
CollectOptions::CollectOptions (Json const& json) {
Json obj = json.get("collectOptions");
method = methodFromString(JsonHelper::getStringValue(obj.json(), "method", ""));
}
示例11: log
void BlockColors::load(const std::string& zipFileName, const std::string& cacheFileName)
{
using namespace json11;
//Keep filenames for later
this->zipFileName = zipFileName;
this->cacheFileName = cacheFileName;
//Zip file interface
auto archive = ZipFile::Open(zipFileName);
//Cache JSON. This is a single { } of key:value of "blockid-meta" to .zip CRC and RGBA color
// ex: {"2-4": {"crc": 5234231, "color": 2489974272}, ... }
std::string parseErr;
Json cacheJson = Json::parse(readFile(cacheFileName), parseErr);
if(!parseErr.empty()) {
log("Could not read cache \"", cacheFileName, "\": ", parseErr);
}
/* Will be true if computeColor is called, basically if cache is missing
* or CRC changed in zip for any file */
bool hadToRecompute = false;
for(unsigned i = 0; i != archive->GetEntriesCount(); ++i)
{
/* Name and CRC of the block image in .zip
* substr on the name is used to cut off the .png at the end */
auto entry = archive->GetEntry(i);
unsigned zipcrc = entry->GetCrc32();
std::string name = entry->GetName();
name = name.substr(0, name.find('.'));
/* To get a block color, first the cache is checked.
* if it's not there, the color is recomputed. If that happens,
* "hadToRecompute" is set to true, and a new .json cache will be written out */
Json key = cacheJson[name];
if(key.is_null()) {
//Look for key with a 0 meta. e.g, "404-0" and not "404"
std::string nameWithMeta = name + "-0";
key = cacheJson[nameWithMeta];
}
SDL_Color blockColor;
if(key.is_object() && (unsigned)key["crc"].int_value() == zipcrc) {
Uint32 cachePixel = key["color"].int_value();
SDL_GetRGBA(cachePixel, rgba, &blockColor.r, &blockColor.g, &blockColor.b, &blockColor.a);
} else {
blockColor = computeColor(entry);
hadToRecompute = true;
}
//Store color and CRC in this object
blockColors[name] = std::make_pair(blockColor, zipcrc);
}
//If any blocks were not found in cache
if(hadToRecompute) {
saveNewJsonCache();
}
}
示例12: ASSERT
Entity SceneLoader::instantiate(Json def, Resources& resources, const string& pathContext)
{
ASSERT(def.is_object());
if (def["prefab"].is_string()) {
const string& prefabName = def["prefab"].string_value();
auto prefabIter = prefabs.find(prefabName);
if (prefabIter != prefabs.end()) {
def = assign(prefabIter->second, def);
} else if (endsWith(prefabName, ".json")) {
string err;
Json extPrefab = Json::parse(resources.getText(resolvePath(pathContext, prefabName), Resources::NO_CACHE), err);
if (!err.empty()) {
logError("Failed to parse prefab \"%s\": %s", prefabName.c_str(), err.c_str());
} else {
def = assign(extPrefab, def);
prefabs[prefabName] = extPrefab;
}
} else {
logError("Could not find prefab \"%s\"", prefabName.c_str());
}
}
Entity entity = world->create();
if (def["name"].is_string()) {
entity.tag(def["name"].string_value());
#ifdef USE_DEBUG_NAMES
DebugInfo info;
info.name = def["name"].string_value();
entity.add<DebugInfo>(info);
} else {
static uint debugId = 0;
DebugInfo info;
if (def["prefab"].is_string())
info.name = def["prefab"].string_value() + "#";
else if (def["geometry"].is_string())
info.name = def["geometry"].string_value() + "#";
else info.name = "object#";
info.name += std::to_string(debugId++);
entity.tag(info.name);
entity.add<DebugInfo>(info);
#endif
}
// Parse transform
if (!def["position"].is_null() || !def["rotation"].is_null() || !def["scale"].is_null() || !def["geometry"].is_null()) {
Transform transform;
setVec3(transform.position, def["position"]);
setVec3(transform.scale, def["scale"]);
if (!def["rotation"].is_null()) {
const Json& rot = def["rotation"];
if (rot.is_array() && rot.array_items().size() == 4)
transform.rotation = quat(rot[3].number_value(), rot[0].number_value(), rot[1].number_value(), rot[2].number_value());
else transform.rotation = quat(toVec3(rot));
}
entity.add(transform);
}
// Parse light
const Json& lightDef = def["light"];
if (!lightDef.is_null()) {
Light light;
const string& lightType = lightDef["type"].string_value();
if (lightType == "ambient") light.type = Light::AMBIENT_LIGHT;
else if (lightType == "point") light.type = Light::POINT_LIGHT;
else if (lightType == "directional") light.type = Light::DIRECTIONAL_LIGHT;
else if (lightType == "spot") light.type = Light::SPOT_LIGHT;
else if (lightType == "area") light.type = Light::AREA_LIGHT;
else if (lightType == "hemisphere") light.type = Light::HEMISPHERE_LIGHT;
else logError("Unknown light type \"%s\"", lightType.c_str());
setColor(light.color, lightDef["color"]);
if (!def["position"].is_null())
light.position = toVec3(def["position"]);
if (!lightDef["direction"].is_null())
light.direction = toVec3(lightDef["direction"]);
setNumber(light.distance, lightDef["distance"]);
setNumber(light.decay, lightDef["decay"]);
entity.add(light);
numLights++;
}
if (!def["geometry"].is_null()) {
Model model;
parseModel(model, def, resources, pathContext);
entity.add(model);
numModels++;
}
// Patch bounding box
// TODO: Bounding box is not correct if scale changed at runtime
if (entity.has<Model>() && entity.has<Transform>()) {
Model& model = entity.get<Model>();
const Transform& trans = entity.get<Transform>();
model.bounds.min = model.lods[0].geometry->bounds.min * trans.scale;
model.bounds.max = model.lods[0].geometry->bounds.max * trans.scale;
model.bounds.radius = model.lods[0].geometry->bounds.radius * glm::compMax(trans.scale);
}
// Parse body (needs to be after geometry, transform, bounds...)
//.........这里部分代码省略.........
示例13: main
int main(int argc, char **argv) {
if (argc == 2 && argv[1] == string("--stdin")) {
parse_from_stdin();
return 0;
}
const string simple_test =
R"({"k1":"v1", "k2":42, "k3":["a",123,true,false,null]})";
string err;
auto json = Json::parse(simple_test, err);
std::cout << "k1: " << json["k1"].string_value() << "\n";
std::cout << "k3: " << json["k3"].dump() << "\n";
for (auto &k : json["k3"].array_items()) {
std::cout << " - " << k.dump() << "\n";
}
std::list<int> l1 { 1, 2, 3 };
std::vector<int> l2 { 1, 2, 3 };
std::set<int> l3 { 1, 2, 3 };
assert(Json(l1) == Json(l2));
assert(Json(l2) == Json(l3));
std::map<string, string> m1 { { "k1", "v1" }, { "k2", "v2" } };
std::unordered_map<string, string> m2 { { "k1", "v1" }, { "k2", "v2" } };
assert(Json(m1) == Json(m2));
// Json literals
Json obj = Json::object({
{ "k1", "v1" },
{ "k2", 42.0 },
{ "k3", Json::array({ "a", 123.0, true, false, nullptr }) },
});
std::cout << "obj: " << obj.dump() << "\n";
assert(Json("a").number_value() == 0);
assert(Json("a").string_value() == "a");
assert(Json().number_value() == 0);
assert(obj == json);
assert(Json(42) == Json(42.0));
assert(Json(42) != Json(42.1));
const string unicode_escape_test =
R"([ "blah\ud83d\udca9blah\ud83dblah\udca9blah\u0000blah\u1234" ])";
const char utf8[] = "blah" "\xf0\x9f\x92\xa9" "blah" "\xed\xa0\xbd" "blah"
"\xed\xb2\xa9" "blah" "\0" "blah" "\xe1\x88\xb4";
Json uni = Json::parse(unicode_escape_test, err);
assert(uni[0].string_value().size() == (sizeof utf8) - 1);
assert(memcmp(uni[0].string_value().data(), utf8, sizeof utf8) == 0);
Json my_json = Json::object {
{ "key1", "value1" },
{ "key2", false },
{ "key3", Json::array { 1, 2, 3 } },
};
std::string json_str = my_json.dump();
printf("%s\n", json_str.c_str());
class Point {
public:
int x;
int y;
Point (int x, int y) : x(x), y(y) {}
Json to_json() const { return Json::array { x, y }; }
};
std::vector<Point> points = { { 1, 2 }, { 10, 20 }, { 100, 200 } };
std::string points_json = Json(points).dump();
printf("%s\n", points_json.c_str());
}
示例14: EarthViewer
EarthViewer(const Vec2<int>& size, const float scale, const bool oblong, Touch& touch, Keyinp& keyinp, const std::string& path, const std::string& lang) :
touch_(touch),
keyinp_(keyinp),
size_(size.x / scale, size.y / scale),
params_(path + "devdata/params.json"),
scale_(scale),
aspect_((float)size.x / (float)size.y),
camera_(Camera::PERSPECTIVE),
cockpit_(Camera::ORTHOGONAL),
localize_(lang, path),
earth_(params_.value().get<picojson::object>()["earth"].get<picojson::object>(), path, camera_),
rotate_mix_(),
place_index_()
{
DOUT << "EarthViewer()" << std::endl;
picojson::object& params = params_.value().get<picojson::object>();
camera_.oblong(oblong);
SetupCamera(camera_, params["camera"].get<picojson::object>(), aspect_);
cockpit_.setSize(size.x / scale, size.y / scale);
{
picojson::array& array = params["lights"].get<picojson::array>();
for (picojson::array::iterator it = array.begin(); it != array.end(); ++it)
{
Light light;
SetupLight(light, it->get<picojson::object>());
lights_.push_back(light);
}
earth_.light(lights_);
}
env_.touch = &touch_;
env_.keyinp = &keyinp_;
env_.path = &path;
env_.savePath = &path;
env_.size = &size_;
env_.scale = scale_;
env_.params = ¶ms_;
env_.task = &task_;
env_.camera = &camera_;
env_.cockpit = &cockpit_;
env_.earth = &earth_;
env_.earthLight = &lights_[0];
env_.fonts = &fonts_;
env_.texMng = &texMng_;
env_.localize = &localize_;
env_.earth_texture = 0;
earth_.texture(env_.earth_texture);
earth_.setRotSpeed(0);
{
const std::string& file = params["game"].get<picojson::object>()["places"].get<std::string>();
Json places = Json(path + file);
places_ = places.value().get<picojson::object>();
for (picojson::object::iterator it = places_.begin(); it != places_.end(); ++it)
{
place_names_.push_back(&it->first);
}
}
task_.add<Control>(TASK_PRIO_SYS, env_);
task_.add<Game2DSetup>(TASK_PRIO_2D_TOPPRIO, env_);
task_.add<GameWorld>(TASK_PRIO_3D_TOPPRIO, env_);
env_.task->add<PlaceDisp>(TASK_PRIO_2D, env_);
// task_.add<Equator>(TASK_PRIO_3D, env_);
task_.add<TouchEft>(TASK_PRIO_3D, env_);
}
示例15: get_anon
// get anonimous user
Json
get_anon(){
Json ret = Json::object();
ret.set("level", LEVEL_ANON);
return ret;
}