Json Json::getObject(const char *key) const { if (!json_) { return Json(); } json_t *object = json_object_get(json_, key); if (json_is_object(object)) return Json(object); return Json(); }
Json Json::ParseFromFile(const char * file){ std::ifstream in(file); std::istreambuf_iterator<char> beg(in), end; std::string str(beg, end); if(str.size() == 0) return Json(); return Parse(str.c_str()); }
explicit Place(const std::string& file) : radius_(1) { Json json = Json(file); area_.reserve(256); #ifdef _DEBUG if (!json.value().is<picojson::array>()) { DOUT << "place read error:" << file << std::endl; return; } #endif picojson::array& array = json.value().get<picojson::array>(); for(picojson::array::iterator it = array.begin(); it != array.end(); ++it) { Polygon<float> polygon; picojson::array& vtx = (*it).get<picojson::array>(); for(picojson::array::iterator it = vtx.begin(); it != vtx.end(); ++it) { picojson::array& v = (*it).get<picojson::array>(); float x = v[0].get<double>() / 100.0 - 1.0; float y = v[1].get<double>() / 50.0 - 1.0; // DXFでは 200mm x 100mm でデータを作っているのでその補正 // ゲーム内では ±1 の座標系に収める polygon.setVtx(Vec2<float>(x, -y)); } area_.push_back(polygon); } }
Json Json::copy() const { if (mType == JsonType::Undefined) { return Json(); } else if (mType == JsonType::Object) { Json obj = JsonConst::EmptyObject; std::vector<Map<Json>::Entry> copiedEntries; for (size_t sz = 0; sz < entries->size(); sz++) { copiedEntries.push_back(Map<Json>::Entry(entries->list[sz].key, entries->list[sz].value.copy())); } obj.append(std::move(copiedEntries)); return obj; } else if (mType == JsonType::Array) { Json arr = JsonConst::EmptyArray; for (size_t sz = 0; sz < elements->size(); sz++) { arr.append((*elements)[sz].copy()); } return arr; } else if (mType == JsonType::String) { return str; } else if (mType == JsonType::Number) { return number; } else if (mType == JsonType::Boolean) { return boolean; } else if (mType == JsonType::Null) { return JsonConst::Null; } }
Json Json::get(const std::string& key) const { if (isObject()) { return Json(json_incref(json_object_get(m_json, key.c_str()))); } else { throw std::domain_error("This method only applies to object type"); } }
TEST(JSON_Integer, Value) { Json i(4096); ASSERT_EQ(4096, i.to_int()); i = Json(8192); ASSERT_EQ(8192, i.to_int()); }
Json& Json::operator = (UInteger val) { if (IsNull()) { Json(val).Swap(*this); } else { any_cast<UInteger>()->v_ = val; } return *this; }
Json& Json::operator = (Real val) { if (IsNull()) { Json(val).Swap(*this); } else { any_cast<Real>()->v_ = val; } return *this; }
Json& Json::operator = (Json::Boolean val) { if (IsNull()) { Json(val).Swap(*this); } else { any_cast<Boolean>()->v_ = val; } return *this; }
Json JsonSerializer::Serialize(Collider *&collider) { Json::object object; // Serialize shape if (collider->shape->type == POLYGON) object["mesh"] = Json(static_cast<Polygon*>(collider->shape)->GetName()); // position, scale, and rotation auto &transform = collider->transform; Json::object position; position["x"] = Json(static_cast<double>(transform.LocalPosition().x)); position["y"] = Json(static_cast<double>(transform.LocalPosition().y)); object["position"] = position; Json::object scale; scale["x"] = Json(static_cast<double>(transform.LocalScale().x)); scale["y"] = Json(static_cast<double>(transform.LocalScale().y)); object["scale"] = scale; Json::object rotation; rotation["z"] = Json(static_cast<double>(transform.LocalRotation2D())); object["rotation"] = rotation; return Json(object); }
Json JsonSerializer::Serialize(Colliders &colliders) { Json::array items; for (auto &collider : colliders) items.push_back(Serialize(collider)); return Json(items); }
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); }
Json RiotService::getSummonerInfoCache(const std::string & summonerId) { auto & kvs = (*KVS::getInstance()); std::string key = std::string(Riot::regionStrings[_region]) + "#" + summonerId; std::string value; std::string err; if(kvs[summonerCacheNameSpace].get(key, value)) { return Json::parse(value, err); } return Json(nullptr); }
Json& Json::operator = (const String& val) { //if (!unicodelite::ValidUTF8(val)) return *this; //TODO exception if (IsNull()) { Json(val).Swap(*this); } else { any_cast<String>()->v_ = val; } return *this; }
Json toEsprima_() override { Json::object obj; obj["type"] = "AssignmentExpression"; obj["loc"] = getLocation(); obj["raw"] = raw_; obj["cform"] = toCCode(); obj["operator"] = op_->toString(); obj["left"] = lhs_->toEsprima_(); obj["right"] = rhs_->toEsprima_(); return Json(obj); }
Json Json::at(int index) const { if (isArray()) { json_t* array = json_array_get(m_json, index); if (array == NULL) { std::out_of_range("array index is out of range or json entity is not an array"); } return Json(json_incref(array)); } else { throw std::domain_error("cannot use at(int index) with this json type"); } }
Json RiotService::GetProfileByIds::internalCall() { auto future1 = std::async(std::launch::async, [this]() { return _service->_api.getSummonerByIds(_params["ids"]); }); auto future2 = std::async(std::launch::async, [this]() { _service->_assetManager.updateVersionInfo(); }); Json summoners = future1.get(); future2.get(); printf("ids : %s\n", summoners.dump().c_str()); for (auto & kv : summoners.object_items()) { auto future = std::async(std::launch::async, [this, kv]() { Json::object info(kv.second.object_items()); printf("summoner info : %s\n", kv.second.dump().c_str()); info["profileImagePath"] = _service->_assetManager.getProfileIconPath(kv.second["profileIconId"].int_value());; _onRead(Json(info)); }); future.get(); } return Json(); }
PlaceViewer(const Vec2<int>& size, const float scale, Touch& touch, Keyinp& keyinp, const std::string& path, const std::string& lang) : keyinp_(keyinp), size_(size), path_(path), cockpit_(Camera::ORTHOGONAL), localize_(lang, path), params_(Json(path + "devdata/params.json").value().get<picojson::object>()), font_(FONT_TEXTURE, path + params_["placeview"].get<picojson::object>()["font"].get<std::string>(), params_["placeview"].get<picojson::object>()["height"].get<double>()), json_(path + params_["game"].get<picojson::object>()["places"].get<std::string>()), place_mode_(), level_(-1), start_(), disp_num_(20), refresh_(true), mode_chg_(), disp_place_(), place_() { DOUT << "PlaceViewer()" << std::endl; cockpit_.setSize(size.x, size.y); { place_type_.push_back(std::string("")); picojson::array& type = params_["game"].get<picojson::object>()["types"].get<picojson::array>(); for (picojson::array::iterator it = type.begin(); it != type.end(); ++it) { std::string& name = it->get<std::string>(); place_type_.push_back(std::string(name)); } } // タイプをリストアップ const picojson::array& array = getEarthTextures(params_["earth"].get<picojson::object>(), 3); const TexMng::tex_ptr tex_l = texmng_.read(path + "devdata/" + array[0].get<std::string>()); tex_name_l_ = tex_l->name(); const TexMng::tex_ptr tex_r = texmng_.read(path + "devdata/" + array[1].get<std::string>()); tex_name_r_ = tex_r->name(); level_max_ = params_["game"].get<picojson::object>()["question"].get<picojson::array>().size() - 1; this->listup(place_mode_, level_); }
TEST(JsonFlattenerTestGroup, UnflattenString) { DynObject Obj1; JsonFlattener Flattener1; String Json("{ \"foo\": \"" STRING1 "\", \"bar\":\"" STRING2 "\", \"other\": \"" STRING3 "\"}"); CHECK(Json.InitCheck() == 0); CHECK(Flattener1.UnFlatten(&Json, &Obj1) == 0); const String *s; CHECK(Obj1.FindString("foo", &s) == 0); CHECK(s != NULL); CHECK(*s == STRING1); CHECK(Obj1.FindString("bar", &s) == 0); CHECK(s != NULL); CHECK(*s == STRING2); CHECK(Obj1.FindString("other", &s) == 0); CHECK(s != NULL); CHECK(*s == STRING3); };
TEST(JsonFlattenerTestGroup, UnflattenInt) { DynObject Obj1; JsonFlattener Flattener1; String Json("{ foo: 32, bar:42, other:892382}"); CHECK(Json.InitCheck() == 0); CHECK(Flattener1.UnFlatten(&Json, &Obj1) == -1); CHECK(Json.SetTo("{ \"foo\": 32, \"bar\":42, \"other\":892382}") == 0); CHECK(Json.InitCheck() == 0); CHECK(Flattener1.UnFlatten(&Json, &Obj1) == 0); int64_t i; CHECK(Obj1.FindInt("foo", &i) == 0); CHECK(i == 32); CHECK(Obj1.FindInt("bar", &i) == 0); CHECK(i == 42); CHECK(Obj1.FindInt("other", &i) == 0); CHECK(i == 892382); };
void SceneLoader::load(const string& path, Resources& resources) { logDebug("Start loading scene %s", path.c_str()); uint t0 = Engine::timems(); m_environment = Json(); load_internal(path, resources); if (!m_environment.is_null() && world->has_system<RenderSystem>()) { RenderSystem& renderer = world->get_system<RenderSystem>(); renderer.env() = parseEnvironment(m_environment, resources, dirname(path)); renderer.device().setEnvironment(&renderer.env()); } Entity cameraEnt; if (world->has_tagged_entity("camera")) { cameraEnt = world->get_entity_by_tag("camera"); } else { cameraEnt = world->create(); cameraEnt.tag("camera"); } if (!cameraEnt.has<Camera>()) { cameraEnt.add<Camera>(); Camera& camera = cameraEnt.get<Camera>(); float ar = Engine::width() / (float)Engine::height(); camera.makePerspective(45, ar, 0.1, 1000); if (cameraEnt.has<Transform>()) { Transform& trans = cameraEnt.get<Transform>(); camera.updateViewMatrix(trans.position, trans.rotation); } else { camera.view = glm::lookAt(vec3(0, 0, 1), vec3(0, 0, 0), vec3(0, 1, 0)); } } resources.startAsyncLoading(); uint t1 = Engine::timems(); logDebug("Loaded scene %s in %dms with %d models, %d bodies, %d lights, %d prefabs", path.c_str(), t1 - t0, numModels, numBodies, numLights, prefabs.size()); }
static Json _lua_to_json(lua_State *l, int idx) { int data = lua_absindex(l, idx); switch (lua_type(l, data)) { case LUA_TNIL: return Json(); case LUA_TNUMBER: return Json(lua_tonumber(l, data)); case LUA_TBOOLEAN: return Json(lua_toboolean(l, data)); case LUA_TSTRING: return Json(lua_tostring(l, data)); case LUA_TTABLE: { // XXX handle arrays Json object(Json::objectValue); lua_pushnil(l); while (lua_next(l, data)) { const std::string key(luaL_checkstring(l, -2)); Json value(_lua_to_json(l, -1)); object[key] = value; lua_pop(l, 1); } return object; } default: luaL_error(l, "can't convert Lua type %s to JSON", lua_typename(l, lua_type(l, idx))); return Json(); } // shouldn't get here assert(0); return Json(); }
TEST(json, join) { Json o1 { {"key1", {1, 2, 3, 4}}, {"key2", { {"key21", 1}, {"key22", 2}, {"key23", 3}, }}, {"key3", "Hello World"} }; Json o2 { {"key2", { {"key23", 4}, {"key24", { {"key241", 1}, {"key242", 2}, }}, }}, {"key3", "Hello World2"} }; EXPECT_TRUE(Json({ {"key1", {1, 2, 3, 4}}, {"key2", { {"key21", 1}, {"key22", 2}, {"key23", 4}, {"key24", { {"key241", 1}, {"key242", 2}, }}, }}, {"key3", "Hello World2"} }) == join(o1, o2)); }
TEST(JsonFlattenerTestGroup, UnflattenObj) { DynObject Obj1; const DynObject *p_Obj2; JsonFlattener Flattener1; #define OBJ2 "{ \"foo\": \"" STRING1 "\", \"bar\":\"" STRING2 "\", \"other\": \"" STRING3 "\"}" String Json("{ \"obj\": " OBJ2 "}"); CHECK(Json.InitCheck() == 0); CHECK(Flattener1.UnFlatten(&Json, &Obj1) == 0); CHECK(Obj1.FindDynObject("obj", &p_Obj2) == 0); CHECK(p_Obj2 != NULL); const String *s; CHECK(p_Obj2->FindString("foo", &s) == 0); CHECK(s != NULL); CHECK(*s == STRING1); CHECK(p_Obj2->FindString("bar", &s) == 0); CHECK(s != NULL); CHECK(*s == STRING2); CHECK(p_Obj2->FindString("other", &s) == 0); CHECK(s != NULL); CHECK(*s == STRING3); };
static void _body_to_json(Json &out, LuaWrappable *o) { Body *b = static_cast<Body *>(o); out = Json(Pi::game->GetSpace()->GetIndexForBody(b)); }
Json Json::array() { return Json(json_array()); }
Json Json::integer(int value) { return Json(json_integer(value)); }
Json Json::string(const std::string& value) { return Json(json_string(value.c_str())); }
Json Json::object() { return Json(json_object()); }
Json Json::load(const std::string& json) { json_error_t error; return Json(json_loads(json.c_str(), 0, &error)); }