bool ValueAnimation::LoadJSON(const JSONValue& source)
{
    valueType_ = VAR_NONE;
    eventFrames_.Clear();

    String interpMethodString = source.Get("interpolationmethod").GetString();
    InterpMethod method = (InterpMethod)GetStringListIndex(interpMethodString.CString(), interpMethodNames, IM_LINEAR);

    SetInterpolationMethod(method);
    if (interpolationMethod_ == IM_SPLINE)
        splineTension_ = source.Get("splinetension").GetFloat();

    // Load keyframes
    JSONArray keyFramesArray = source.Get("keyframes").GetArray();
    for (unsigned i = 0; i < keyFramesArray.Size(); i++)
    {
        const JSONValue& val = keyFramesArray[i];
        float time = val.Get("time").GetFloat();
        Variant value = val.Get("value").GetVariant();
        SetKeyFrame(time, value);
    }

    // Load event frames
    JSONArray eventFramesArray = source.Get("eventframes").GetArray();
    for (unsigned i = 0; i < eventFramesArray.Size(); i++)
    {
        const JSONValue& eventFrameVal = eventFramesArray[i];
        float time = eventFrameVal.Get("time").GetFloat();
        unsigned eventType = eventFrameVal.Get("eventtype").GetUInt();
        VariantMap eventData = eventFrameVal.Get("eventdata").GetVariantMap();
        SetEventFrame(time, StringHash(eventType), eventData);
    }

    return true;
}
Exemple #2
0
void testArray()
{
	JSONParser *parser;
	JSONAtom *atom;
	JSONArray *arrayAtom;

	tryArrayOk("[]", [](const JSONArray &arrayAtom) { assertIntEqual(arrayAtom.size(), 0); });

	tryArrayOk("[0]", [](const JSONArray &arrayAtom)
	{
		assertIntEqual(arrayAtom.size(), 1);
		assertNotNull(arrayAtom[0]);
		assertIntEqual(arrayAtom[0].asInt(), 0);
	});

	tryArrayOk("[0, true]", [](const JSONArray &arrayAtom)
	{
		assertIntEqual(arrayAtom.size(), 2);
		assertNotNull(arrayAtom[0]);
		assertIntEqual(arrayAtom[0].asInt(), 0);
		assertNotNull(arrayAtom[1]);
		assertTrue(arrayAtom[1].asBool());
	});

	tryArrayFail("[");
	tryArrayFail("[,]");
	tryArrayFail("[, true]");
	tryArrayFail("[null, ]");
	tryArrayFail("[null, ");
}
Exemple #3
0
CJSONElement::~CJSONElement()
{
  if (m_type == TYPESTRING)
  {
    delete (string*)m_data.m_ptr;
  }
  else if (m_type == TYPEMAP)
  {
    JSONMap* map = (JSONMap*)m_data.m_ptr;
    for (JSONMap::iterator it = map->begin(); it != map->end(); it++)
      delete it->second;

    delete (JSONMap*)m_data.m_ptr;
  }
  else if (m_type == TYPEARRAY)
  {
    JSONArray* array = (JSONArray*)m_data.m_ptr;
    for (JSONArray::iterator it = array->begin(); it != array->end(); it++)
      delete *it;

    delete (JSONArray*)m_data.m_ptr;
  }

  delete m_error;
}
Exemple #4
0
void CTestJSON::parseJsonStr( const std::wstring& strJsonStr )
{
	JSONValue* jsInput = JSON::Parse(strJsonStr.c_str());
	if (jsInput == NULL || !jsInput->IsObject())
	{
		return;
	}

	JSONObject::const_iterator itResult = jsInput->AsObject().find(L"result");
	if (itResult != jsInput->AsObject().end())
	{
		std::wstring strResult = itResult->second->AsString();
		std::wcout << L"result" << L":" << strResult << std::endl;
	}

	JSONObject::const_iterator itLove = jsInput->AsObject().find(L"Love");
	if (itLove != jsInput->AsObject().end())
	{
		std::wstring strResult = itLove->second->AsString();
		std::wcout << L"Love" << L":" << strResult << std::endl;
	}

	JSONArray jsArray;
	JSONObject::const_iterator itContents = jsInput->AsObject().find(L"contents");
	if (itContents != jsInput->AsObject().end() && itContents->second != NULL && itContents->second->IsArray())
	{
		jsArray = itContents->second->AsArray();
	}

	std::wcout << "[" << std::endl;
	JSONArray::iterator it = jsArray.begin();
	JSONArray::iterator itEnd = jsArray.end();
	for (; it != itEnd; ++it)
	{
		JSONValue* jsValue = *it;
		if (jsValue->IsObject())
		{
			jsValue->AsObject();
			JSONObject::const_iterator itObj = jsValue->AsObject().begin();
			JSONObject::const_iterator itObjEnd = jsValue->AsObject().end();
			for (; itObj != itObjEnd; ++itObj)
			{
				std::wstring strValue = itObj->second->AsString();
				std::wcout << L"{" << itObj->first << L":" << strValue << L"}" << std::endl;
			}
		}
		else if (jsValue->IsString())
		{		
			std::wstring strValue = jsValue->AsString();
			std::wcout << strValue << std::endl;
		}
		else if (jsValue->IsNumber())
		{
			double dValue = jsValue->AsNumber();
			std::wcout << dValue << std::endl;
		}
		//...
	}
	std::wcout << "]" << std::endl;
}
bool UnknownComponent::LoadJSON(const JSONValue& source, bool setInstanceDefault)
{
    useXML_ = true;
    xmlAttributes_.Clear();
    xmlAttributeInfos_.Clear();
    binaryAttributes_.Clear();

    JSONArray attributesArray = source.Get("attributes").GetArray();
    for (unsigned i = 0; i < attributesArray.Size(); i++)
    {
        const JSONValue& attrVal = attributesArray.At(i);

        AttributeInfo attr;
        attr.mode_ = AM_FILE;
        attr.name_ = attrVal.Get("name").GetString();
        attr.type_ = VAR_STRING;

        if (!attr.name_.Empty())
        {
            String attrValue = attrVal.Get("value").GetString();
            attr.defaultValue_ = String::EMPTY;
            xmlAttributeInfos_.Push(attr);
            xmlAttributes_.Push(attrValue);
        }
    }

    // Fix up pointers to the attributes after all have been read
    for (unsigned i = 0; i < xmlAttributeInfos_.Size(); ++i)
        xmlAttributeInfos_[i].ptr_ = &xmlAttributes_[i];

    return true;
}
Exemple #6
0
unsigned WINAPI bday_thread(LPVOID)
{
	SYSTEMTIME st;
	GetSystemTime(&st);
	wostringstream q;
	q << L"SELECT+name%2c+profile_url+from+user+where+uid+in+(select+uid2+from+friend+where+uid1+%3d+me())+and+strpos(birthday_date%2c%22";
	q << (st.wMonth);
	q << L"%2f";
	q << (st.wDay);
	q << L"%22)%3e%3d0";
	wstring fql = q.str();

	JSONValue *j = fql_query(fql.c_str());
	
	if(j)
	{
		
		JSONObject obj = j->AsObject();
		JSONArray data = (obj[L"data"] ? obj[L"data"]->AsArray(): JSONArray());
		for(JSONArray::const_iterator i = data.begin();i != data.end(); ++i)
		{
			JSONObject i_obj = (*i)->AsObject();
			wstring name = i_obj[L"name"]->AsString();
			name += L" ma urodziny!";
			wstring url = i_obj[L"profile_url"]->AsString();
			display_notif(wstring(L"Facebook Urodziny"), name, url);
		}
		delete j;
	}
	return 0;
}
void EntityIdentifier::parseCategoryDefinition(JSONObject *data, int packID) {
  QString category;
  if (data->has("category"))
    category = data->at("category")->asString();
  else
    category = "Unknown";

  QColor catcolor;
  if (data->has("catcolor")) {
    QString colorname = data->at("catcolor")->asString();
    catcolor.setNamedColor(colorname);
    assert(catcolor.isValid());
  } else {  // use hashed by name instead
    quint32 hue = qHash(category);
    catcolor.setHsv(hue % 360, 255, 255);
  }
  addCategory(qMakePair(category, catcolor));

  if (data->has("entity")) {
    JSONArray *entities = dynamic_cast<JSONArray *>(data->at("entity"));
    int len = entities->length();

    for (int e = 0; e < len; e++)
      parseEntityDefinition(dynamic_cast<JSONObject *>(entities->at(e)),
                            category, catcolor, packID);
  }
}
Exemple #8
0
JSONObject* WriteVisitor::createJSONMorphGeometry(osgAnimation::MorphGeometry* morphGeometry, osg::Object* parent)
{
    if(!parent) {
        parent = morphGeometry;
    }

    JSONObject* jsonGeometry = createJSONGeometry(morphGeometry, parent);
    JSONArray* targetList = new JSONArray;

    osgAnimation::MorphGeometry::MorphTargetList mTargetList = morphGeometry->getMorphTargetList();
    typedef osgAnimation::MorphGeometry::MorphTargetList::iterator TargetIterator;

    for(TargetIterator ti = mTargetList.begin(); ti != mTargetList.end(); ti++) {
        osgAnimation::MorphGeometry::MorphTarget *morphTarget = &(*ti);
        JSONObject *jsonGeometryObject = new JSONObject;
        if(osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(morphTarget->getGeometry())) {
            geometry->setPrimitiveSetList(osg::Geometry::PrimitiveSetList()); //delete unused drawArray
            jsonGeometryObject->getMaps()["osg.Geometry"] = createJSONGeometry(geometry);
            targetList->asArray()->getArray().push_back(jsonGeometryObject);
        }
    }
    jsonGeometry->getMaps()["MorphTargets"] = targetList;

    return jsonGeometry;
}
Exemple #9
0
void api_hdd_handler(const shared_ptr<restbed::Session> session)
{
  Hdd *hdd;
  JSONArray devices;
  JSONObject obj;
  JSONObject deviceData;
  JSONValue *output;
  double hddTotal;
  double hddUsage;
  vector<string> hddDevices;

  hdd = Hdd::getInstance();
  hddTotal = hdd->getTotalCapacity();
  hddUsage = hdd->getUsedCapacity();
  hddDevices = hdd->getListHardDrive();
  obj[L"total"] = new JSONValue(hddTotal);
  obj[L"usage"] = new JSONValue(hddUsage);
  for (vector<string>::iterator it = hddDevices.begin(); it != hddDevices.end(); ++it)
  {
    deviceData[L"name"] = new JSONValue(s2ws(*it));
    devices.push_back(new JSONValue(deviceData));
  }
  obj[L"devices"] = new JSONValue(devices);
  output = new JSONValue(obj);
  session->close(restbed::OK, ws2s(output->Stringify()), { { "Content-Type", "application/json" } });
}
const char* OuyaPlugin_JSONArray_ToString(int jsonArray)
{
#if ENABLE_VERBOSE_LOGGING
    __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONArray_ToString: jsonArray=%d", jsonArray);
#endif
    std::map<int, JSONArray*>::const_iterator search = g_refJSONArray.find(jsonArray);
    if (search != g_refJSONArray.end())
    {
        JSONArray* instance = search->second;
        if (instance)
        {
#if ENABLE_VERBOSE_LOGGING
            __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONArray_ToString JSONArray reference is valid");
#endif
            g_tempPluginString = instance->toString();
#if ENABLE_VERBOSE_LOGGING
            __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONArray_ToString jsonData=%s", g_tempPluginString.c_str());
#endif
            return g_tempPluginString.c_str();
        }
        else
        {
            __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_ToString JSONArray reference is invalid");
        }
    }
    else
    {
        __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_ToString failed to find JSONArray reference");
    }

    return "";
}
void OuyaPlugin_JSONArray_Put(int jsonArray, int index, int jsonObject)
{
    std::map<int, JSONArray*>::const_iterator searchJSONArray = g_refJSONArray.find(jsonArray);
    if (searchJSONArray == g_refJSONArray.end())
    {
        __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_Put JSONArray reference is invalid");
        return;
    }

    std::map<int, JSONObject*>::const_iterator searchJSONObject = g_refJSONObject.find(jsonObject);
    if (searchJSONObject == g_refJSONObject.end())
    {
        __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_Put JSONObject reference is invalid");
        return;
    }

    JSONArray* instanceJSONArray = searchJSONArray->second;
    if (!instanceJSONArray)
    {
        __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_Put JSONArray instance is invalid");
        return;
    }

    JSONObject* instanceJSONObject = searchJSONObject->second;
    if (!instanceJSONObject)
    {
        __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_Put JSONObject instance is invalid");
        return;
    }

    instanceJSONArray->put(index, instanceJSONObject->GetInstance());
}
JSON::JSONArray JSON::fromPoint(const Point& point)
{
    JSONArray array;

    array.push_back(fromNumber(point.x()));
    array.push_back(fromNumber(point.y()));

    return array;
}
Exemple #13
0
void jsonValueToRapidJSON(JSONValue* value, rapidjson::Value& rapidValue, rapidjson::Document& document) {
	JSONNull* nullValue = dynamic_cast<JSONNull*>(value);
	if (nullValue) {
		rapidValue.SetNull();
		return;
	}
	JSONNumber* numberValue = dynamic_cast<JSONNumber*>(value);
	if (numberValue) {
		if (numberValue->canBeUInt64()) {
			rapidValue.SetUint64(numberValue->getUInt64Value());
		}
		else if (numberValue->canBeInt64()) {
			rapidValue.SetInt64(numberValue->getInt64Value());
		}
		else  {
			rapidValue.SetDouble(numberValue->getDoubleValue());
		}
		return;
	}
	JSONString* stringValue = dynamic_cast<JSONString*>(value);
	if (stringValue) {
		rapidValue.SetString(stringValue->getValue().c_str(), stringValue->getValue().size(), document.GetAllocator());
		return;
	}
	JSONBool* boolValue = dynamic_cast<JSONBool*>(value);
	if (boolValue) {
		rapidValue.SetBool(boolValue->getValue());
		return;
	}
	JSONArray* arrayValue = dynamic_cast<JSONArray*>(value);
	if (arrayValue) {
		rapidValue.SetArray();
		std::vector<JSONValue::ref> values = arrayValue->getValues();
		for (auto & value : values) {
			rapidjson::Value obj;
			jsonValueToRapidJSON(value.get(), obj, document);
			rapidValue.PushBack(obj, document.GetAllocator());
		}
		return;
	}
	JSONObject* objectValue = dynamic_cast<JSONObject*>(value);
	if (objectValue) {
		rapidValue.SetObject();
		typedef std::map<std::string, JSONValue::ref> ValuesMap;
		ValuesMap values = objectValue->getValues();
		for (auto & value : values) {
			rapidjson::Value obj;
			jsonValueToRapidJSON(value.second.get(), obj, document);
			rapidjson::Value key;
			key.SetString(value.first.c_str(), value.first.size(), document.GetAllocator());
			rapidValue.AddMember(key, obj, document.GetAllocator());
		}
		return;
	}
	assert(false);
}
Exemple #14
0
JSONArray* JSONArray::deepCopy() const {
  JSONArray* result = new JSONArray();

  const int size = this->size();
  for (int i = 0; i < size; i++) {
    result->add( JSONBaseObject::deepCopy( get(i) ) );
  }

  return result;
}
bool Round::SystemGetNetworkInfoResponse::setClusters(LocalNode *node) {
  JSONArray *clusterArray = getResultClusterArray();

  JSONDictionary *jsonDict = new JSONDictionary();
  SystemClusterInfoDict clusterInfoDict(jsonDict);
  clusterInfoDict.setCluster(node);
  
  clusterArray->add(jsonDict);
  
  return true;
}
Exemple #16
0
JSONDrawArrayLengths::JSONDrawArrayLengths(osg::DrawArrayLengths& array)
{
    getMaps()["First"] = new JSONValue<int>(array.getFirst());
    getMaps()["Mode"] = getDrawMode(array.getMode());

    JSONArray* jsonArray = new JSONArray;
    for (unsigned int i = 0; i < array.size(); i++) {
        jsonArray->getArray().push_back(new JSONValue<int>(array[i]));
    }
    getMaps()["ArrayLengths"] = jsonArray;
}
Exemple #17
0
void EntityIdentifier::parseEntityDefinition(JSONObject *entity,
                                             QString const &category,
                                             QColor catcolor, int packID) {
  QString id("unknown");
  if (entity->has("id"))
    id = entity->at("id")->asString().toLower();

  if (entity->has("catcolor")) {
    QString colorname = entity->at("catcolor")->asString();
    catcolor.setNamedColor(colorname);
    assert(catcolor.isValid());
  }

  QColor color;
  if (entity->has("color")) {
    QString colorname = entity->at("color")->asString();
    color.setNamedColor(colorname);
    assert(color.isValid());
  } else {  // use hashed by name instead
    quint32 hue = qHash(id);
    color.setHsv(hue % 360, 255, 255);
  }

  QString name;
  if (entity->has("name")) {
    // use provided name
    name = entity->at("name")->asString();
  } else {
    // or try to build name automatically
    // split at underscores
    QStringList tokens = id.toLower().replace('_',' ').split(" ");
    // make first character uppercase
    for (QList<QString>::iterator tokItr = tokens.begin(); tokItr != tokens.end(); ++tokItr) {
      (*tokItr) = (*tokItr).at(0).toUpper() + (*tokItr).mid(1);
    }
    name = tokens.join(" ");
  }

  // enter entity into manager
  TentityMap& map = getMapForPackID(packID);
  map.insert(id, EntityInfo(name, category, catcolor, color));

  // add duplicates: when new 1.11+ or 1.13+ id definitions are available
  // legacy id is stored in own definition element (duplicates automatically)
  if (entity->has("idlist")) {
    JSONArray *idlist = dynamic_cast<JSONArray *>(entity->at("idlist"));
    int len = idlist->length();
    for (int j = 0; j < len; j++) {
      QString idl = entity->at("idlist")->at(j)->asString().toLower();
      map.insert(idl, EntityInfo(name, category, catcolor, color));
    }
  }
}
bool JSONArray::equals(JSONElement *other){
	if (other && other->getType() == JSON_ARRAY){
		JSONArray *o = (JSONArray*)other;
		if (_elements.size() == o->_elements.size()){
			for (int i = 0; i < _elements.size(); i++){
				if (!get(i)->equals(o->get(i))){
					return false;
				}
			}
			return true;
		}
	}
	return false;
}
Exemple #19
0
BOOL WINAPI Conf::ParseAction(JSONArray js) {

	UINT i = 0;
	ActionsManager *actionsManager = ActionsManager::self();

	for (i = 0; i < js.size(); i++) {
		JSONObject jo = js[i]->AsObject();
		JSONValue *c = jo[L"subactions"];

		if (c == NULL || c->IsArray() == FALSE) {
			// WARNING
			continue;
		}

#ifdef _DEBUG
		WCHAR msg[128];
		wstring moduleName = jo[L"desc"]->AsString();
		//wprintf(L"Parsing Action: \"%s\"\n", moduleName.c_str());
		swprintf_s(msg, L"Parsing Action: \"%s\"\n", moduleName.c_str());OutputDebugString(msg);
#endif

		actionsManager->add(i, c->AsArray());
	}

	return TRUE;
}
RichTextMutation RandomMutationGenerator::createRichTextMutation(JSONObject object)
{
    RichTextMutation m(true);

    JSONArray text = object.attributeArray("_r");
    // How many characters/objects are there?
    int count = 0;
    QHash<int, JSONAbstractObject> objects;
    for( int j = 0; j < text.count(); ++j )
    {
        if ( text[j].isString())
            count += text[j].toString().length();
        else if ( !text[j].toObject().hasAttribute("_format"))
        {
            objects[count] = text[j];
            count++;
        }
    }

    int i = 0;
    while( i < count )
    {
        int y = qrand() % 4;
        if ( y == 0 )
        {
            m.content().append(SkipMutation(1));
            i++;
        }
        else if ( y == 1)
        {
            m.content().append(DeleteMutation(1));
            i++;
        }
        else if ( y == 2 && objects.contains(i))
        {
            m.content().append( createMutation( objects[i]) );
            i++;
        }
        else
        {
            m.content().append( InsertMutation(createString()) );
        }
    }

    return m;
}
		JNIEXPORT void JNICALL Java_tv_ouya_sdk_android_CallbacksRequestReceipts_CallbacksRequestReceiptsOnSuccess(JNIEnv* env, jobject thiz, jstring jsonData)
		{
			LOGI("***********Java_tv_ouya_sdk_android_CallbacksRequestReceipts_CallbacksRequestReceiptsOnSuccess***********");
		
			std::string strJsonData = env->GetStringUTFChars(jsonData, NULL);

			//char buffer[256];
			//sprintf(buffer, "Java_tv_ouya_sdk_android_CallbacksRequestReceipts_CallbacksRequestReceiptsOnSuccess: Returned to C: %s", strJsonData.c_str());
			//LOGI(buffer);

			//LOGI("Parsing JSON Data");

			// Parse example data
			JSONValue* value = JSON::Parse(strJsonData.c_str());

			if (value == NULL)
			{
				LOGI("Parsing JSON Failed");
				return;
			}

			if (!value->IsArray())
			{
				LOGI("Parsing JSON Failed: Not an array");
				return;
			}

			// Retrieve the main object
			JSONArray data = value->AsArray();

			std::vector<Receipt> receipts;

			for (unsigned int i = 0; i < data.size(); i++)
			{
				OuyaSDK::Receipt newReceipt;
				newReceipt.ParseJSON(data[i]);

				receipts.push_back(newReceipt);
			}
		
			CallbacksRequestReceipts* callback = CallbackSingleton::GetInstance()->m_callbacksRequestReceipts;
			if (callback)
			{
				callback->OnSuccess(receipts);
			}
		}
void OuyaPlugin_asyncOuyaRequestProducts(const char* productsJson, s3eCallback onSuccess, s3eCallback onFailure, s3eCallback onCancel)
{
	IwTrace(ODK, ("ODK_platform: OuyaPlugin_asyncOuyaRequestProducts"));

	std::string msg = "OuyaPlugin_asyncOuyaRequestProducts: productsJson=";
	msg.append(productsJson);
	IwTrace(ODK, (msg.c_str()));

	//convert JSON to product id array

	// Parse example data
	JSONValue* value = JSON::Parse(productsJson);

	if (value == NULL)
	{
		IwTrace(ODK, ("Parsing JSON Failed"));
		return;
	}

	if (!value->IsArray())
	{
		IwTrace(ODK, ("Parsing JSON Failed: Not an array"));
		return;
	}

	// Retrieve the main object
	JSONArray data = value->AsArray();

	std::vector<std::string> productIds;

	for (unsigned int i = 0; i < data.size(); i++)
	{
		if (data[i]->IsString())
		{
			const std::wstring wstr = data[i]->AsString();

			std::string productId( wstr.begin(), wstr.end() );

			productIds.push_back(productId);
		}
	}

	OuyaSDK::CallbackSingleton::GetInstance()->m_callbacksRequestProducts->RegisterCallbacks(onSuccess, onFailure, onCancel);

	g_pluginOuya.AsyncOuyaRequestProducts(productIds);
}
Exemple #23
0
	JSONObject SpellData::ToJSON()
	{
		JSONObject object;

		object.set("id", mId);
		object.set("name", mName);
		object.set("cast_time", mCastTime);
		object.set("cooldown", mCooldown);
		object.set("spell_type", (int) mType);
		object.set("cast_type", (int) mCastType);
		object.set("spell_radius", mRadius);
		object.set("spell_range", mRange);
		object.set("shape", (int) mShape);

		JSONArray effects;
		for (auto &effectData : mEffects) {
			JSONObject effect;
			effect.set("id", effectData.id);
			effect.set("spell_id", effectData.spellId);
			effect.set("effect_type", (int) effectData.effectType);
			effect.set("percent_source_min", effectData.percentSourceMin);
			effect.set("school", effectData.school);
			effect.set("duration", effectData.duration);

			effects.add(effect);
		}

		object.set("effects", effects);

		JSONArray triggers;
		for (auto &triggerData : mTriggers) {
			JSONObject trigger;
			trigger.set("id", triggerData.id);
			trigger.set("spell_id", triggerData.spellId);
			trigger.set("trigger_spell_id", triggerData.triggerSpellId);
			trigger.set("chance", triggerData.chance);
			trigger.set("trigger_type", (int) triggerData.triggerType);

			triggers.add(trigger);
		}

		object.set("triggers", triggers);

		return object;
	}
Exemple #24
0
/*
{
"contents": [{
"Test": "Test,Obj"
},
"HelloWorld,cswuyg",
"Good Good Studey,Day Day Up"],
"result": "no_way"
}
*/
std::wstring CTestJSON::GetJsonStr()
{
	JSONArray jsArray;
	JSONObject jsObj;
	jsObj[L"Test"] = new(std::nothrow)JSONValue(L"Test,Obj");
	jsArray.push_back(new(std::nothrow)JSONValue(jsObj));
	jsArray.push_back(new(std::nothrow)JSONValue(L"HelloWorld,cswuyg"));
	jsArray.push_back(new(std::nothrow)JSONValue(L"Good Good Studey,Day Day Up"));
	jsArray.push_back(new(std::nothrow)JSONValue((double)1988));

	JSONObject jsObjNew;
	jsObjNew[L"contents"] = new(std::nothrow)JSONValue(jsArray);
	jsObjNew[L"result"] = new(std::nothrow)JSONValue(L"no_way");

	JSONValue jsValue = jsObjNew;
	std::wstring strRet = jsValue.Stringify().c_str();
	return strRet;
}
Exemple #25
0
std::string serialize_data(data_t *data) {
    std::lock_guard<std::mutex> lk(data->m);

    JSONObject root;

    JSONObject states;
    states[L"isBlink"] = new JSONValue(data->isBlink);
    states[L"isLeftWink"] = new JSONValue(data->isLeftWink);
    states[L"isRightWink"] = new JSONValue(data->isRightWink);
    states[L"isLookingLeft"] = new JSONValue(data->isLookingLeft);
    states[L"isLookingRight"] = new JSONValue(data->isLookingRight);

    JSONObject expressiv;

    expressiv[L"lowerFaceActionName"] = new JSONValue(s2w(data->lowerFaceActionName));
    expressiv[L"lowerFaceAction"] = new JSONValue((double) data->lowerFaceAction);
    expressiv[L"lowerFaceActionPower"] = new JSONValue(data->lowerFaceActionPower);
    expressiv[L"upperFaceActionName"] = new JSONValue(s2w(data->upperFaceActionName));
    expressiv[L"upperFaceAction"] = new JSONValue((double) data->upperFaceAction);
    expressiv[L"upperFaceActionPower"] = new JSONValue(data->upperFaceActionPower);

    root[L"time"] = new JSONValue(data->timestamp);
    root[L"battery"] =  new JSONValue(data->battery);
    root[L"wirelessSignal"] = new JSONValue((double)(data->wireless_signal));
    root[L"states"] = new JSONValue(states);
    root[L"expressiv"] = new JSONValue(expressiv);

    JSONArray array;
    for (int i = 0; i < data->cq.size(); i++) {
        array.push_back(new JSONValue((double) data->cq[i]));
    }
    root[L"contactQuality"] = new JSONValue(array);

    JSONValue *value = new JSONValue(root);
    std::wstring out = value->Stringify();


    std::string ss;
    ss.assign(out.begin(), out.end());

    delete value;

    return ss;
}
Exemple #26
0
void jsonValueToRapidJSON(JSONValue* value, rapidjson::Value& rapidValue, rapidjson::Document& document) {
	JSONInt* intValue = dynamic_cast<JSONInt*>(value);
	if (intValue) {
		rapidValue.SetInt(intValue->getValue());
		return;
	}
	JSONString* stringValue = dynamic_cast<JSONString*>(value);
	if (stringValue) {
		rapidValue.SetString(stringValue->getValue().c_str(), stringValue->getValue().size(), document.GetAllocator());
		return;
	}
	JSONBool* boolValue = dynamic_cast<JSONBool*>(value);
	if (boolValue) {
		rapidValue.SetBool(boolValue->getValue());
		return;
	}
	JSONArray* arrayValue = dynamic_cast<JSONArray*>(value);
	if (arrayValue) {
		rapidValue.SetArray();
		std::vector<JSONValue::ref> values = arrayValue->getValues();
		for (size_t i = 0; i < values.size(); i++) {
			rapidjson::Value obj;
			jsonValueToRapidJSON(values[i].get(), obj, document);
			rapidValue.PushBack(obj, document.GetAllocator());
		}
		return;
	}
	JSONObject* objectValue = dynamic_cast<JSONObject*>(value);
	if (objectValue) {
		rapidValue.SetObject();
		typedef std::map<std::string, JSONValue::ref> ValuesMap;
		ValuesMap values = objectValue->getValues();
		for (ValuesMap::iterator it = values.begin(); it != values.end(); it++) {
			rapidjson::Value obj;
			jsonValueToRapidJSON(it->second.get(), obj, document);
			rapidjson::Value key;
			key.SetString(it->first.c_str(), it->first.size(), document.GetAllocator());
			rapidValue.AddMember(key, obj, document.GetAllocator());
		}
		return;
	}
	assert(false);
}
bool Round::SystemGetNetworkInfoResponse::getClusters(ClusterList *clusterList) {
  JSONArray *clusterArray = getResultClusterArray();
  size_t clusterCnt = clusterArray->size();
  for (size_t n=0; n<clusterCnt; n++) {
    JSONDictionary *jsonDict = dynamic_cast<JSONDictionary *>(clusterArray->getObject(n));
    if (!jsonDict)
      continue;
    
    SystemClusterInfoDict clusterInfoDict(jsonDict);
    Cluster *cluster = new Cluster();
    if (!clusterInfoDict.getCluster(cluster)) {
      delete cluster;
      continue;
    }
    
    clusterList->addCluster(cluster);
  }
  
  return true;
}
Exemple #28
0
unsigned WINAPI notif_thread(LPVOID)
{
	JSONValue *j = fql_query(L"select+title_text%2c+href%2c+icon_url+from+notification+where+recipient_id+%3d+me()+and+is_unread");
	if(j && j->IsObject())
	{
		JSONObject obj = j->AsObject();
		JSONArray data = obj[L"data"]->AsArray();
		for(JSONArray::const_iterator i = data.begin();i != data.end();++i)
		{
			if(!((*i)->IsObject()))
				continue;
			JSONObject i_obj = (*i)->AsObject();
			wstring href, title_text;
			href = i_obj[L"href"]->AsString();
			title_text = i_obj[L"title_text"]->AsString();
			display_notif(wstring(L"Facebook Notification"), title_text, href);	
		}
		delete j;
	}
	return 0;
}
Exemple #29
0
 bool JSONArray::isEqualTo(JSONValue* value) {
     assert(value != nullptr);
     
     if (JSONValue::isEqualTo(value) == true)
         return true;
     
     size_t count = this->getCount();
     JSONArray *arrayValue = (JSONArray*)(value);
     if (count != arrayValue->getCount())
         return false;
     
     
     JSONValueVectorRef allValues = arrayValue->values();
     for (size_t i = 0 ; i < count ; i++) {
         if (allValues[i]->isEqualTo(this->_values[i].get()) == false) {
             return false;
         }
     }
     
     return true;
 }
void LevelLoader::loadAIWaypoints(JSONObject & ai, std::wstring const & pathName, int index, float startX, float startY)
{
	// Load the AI data as waypoints from an array.
	JSONArray littleBearArray = ai[pathName]->AsArray();
	m_gameData.m_littleBearWayPoints = littleBearArray.size();

	// Calculate normalized vectors between each waypoint for path 1.
	JSONObject waypoint = littleBearArray[0]->AsObject();
	m_gameData.m_littleBearWPX[index] = waypoint[L"x"]->AsNumber();
	m_gameData.m_littleBearWPY[index] = waypoint[L"y"]->AsNumber();
	sf::Vector2<float> vec(m_gameData.m_littleBearWPX[index] - startX,
						   m_gameData.m_littleBearWPY[index] - startY);

	sf::Vector2f result = thor::unitVector(vec);

	m_gameData.m_littleBearDirVecX[index] = result.x;
	m_gameData.m_littleBearDirVecY[index] = result.y;

	index++;
	calculateDirVec(index, littleBearArray);
}