示例#1
0
void _PlanOperation::addField(const Json::Value &field) {
  if (field.isNumeric()) {
    addField(field.asUInt());
  } else if (field.isString()) {
    addNamedField(field.asString());
  } else throw std::runtime_error("Can't parse field name, neither numeric nor std::string");
}
示例#2
0
文件: JsonUtils.cpp 项目: onze/Steel
    float JsonUtils::asFloat(const Json::Value &value, float defaultValue)
    {
        float returned = defaultValue;

        if(value.isString())
            returned =  Ogre::StringConverter::parseReal(value.asString(), defaultValue);

        if(value.isNumeric())
            returned = value.asFloat();

        return returned;
    }
std::string GlobalizationNDK::dateToString(const std::string& args)
{
    if (args.empty())
        return errorInJson(PARSING_ERROR, "No date provided!");

    Json::Reader reader;
    Json::Value root;
    bool parse = reader.parse(args, root);

    if (!parse) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::dateToString: invalid json data: %s",
                args.c_str());
        return errorInJson(PARSING_ERROR, "Parameters not valid json format!");
    }

    Json::Value date = root["date"];
    if (date.isNull()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::dateToString: no date provided.");
        return errorInJson(PARSING_ERROR, "No date provided!");
    }

    if (!date.isNumeric()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::dateToString: date is not a numeric: %d.",
                date.type());
        return errorInJson(PARSING_ERROR, "Date in wrong format!");
    }

    Json::Value options = root["options"];

    DateFormat::EStyle dstyle, tstyle;
    std::string error;

    if (!handleDateOptions(options, dstyle, tstyle, error))
        return errorInJson(PARSING_ERROR, error);

    UErrorCode status = U_ZERO_ERROR;
    const Locale& loc = Locale::getDefault();
    DateFormat* df = DateFormat::createDateTimeInstance(dstyle, tstyle, loc);

    if (!df) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::dateToString: unable to create DateFormat!");
        return errorInJson(UNKNOWN_ERROR, "Unable to create DateFormat instance!");
    }
    std::auto_ptr<DateFormat> deleter(df);

    UnicodeString result;
    df->format(date.asDouble(), result);

    std::string utf8;
    result.toUTF8String(utf8);
    return resultInJson(utf8);
}
std::vector<float> ParserActionParameters::parseVector(Json::Value temp_info){
	std::vector<float> vector;
	if(!temp_info.isNull() && temp_info.isArray()){
		Json::Value value;
		for(int i= 0; i< temp_info.size(); ++i){
			value = temp_info.get(i,"UTF-8");
			if(!value.isNull() && value.isNumeric()){
				vector.push_back(value.asFloat());
			}
		}
	}
	return vector;
}
示例#5
0
void 
ValueTest::checkIs( const Json::Value &value, const IsCheck &check )
{
   JSONTEST_ASSERT_EQUAL( check.isObject_, value.isObject() );
   JSONTEST_ASSERT_EQUAL( check.isArray_, value.isArray() );
   JSONTEST_ASSERT_EQUAL( check.isBool_, value.isBool() );
   JSONTEST_ASSERT_EQUAL( check.isDouble_, value.isDouble() );
   JSONTEST_ASSERT_EQUAL( check.isInt_, value.isInt() );
   JSONTEST_ASSERT_EQUAL( check.isUInt_, value.isUInt() );
   JSONTEST_ASSERT_EQUAL( check.isIntegral_, value.isIntegral() );
   JSONTEST_ASSERT_EQUAL( check.isNumeric_, value.isNumeric() );
   JSONTEST_ASSERT_EQUAL( check.isString_, value.isString() );
   JSONTEST_ASSERT_EQUAL( check.isNull_, value.isNull() );
}
示例#6
0
void Objects::StringDisplay::update()
{
  // Make sure repeated calls to this function don't simply add strings
  self_displayStrings.clear();

  Json::Value strings;
  strings = self_data["strings"];

  if (self_data["external"].isBool())
    if (self_data["external"] == true)
    {
      string resource = self_data["resource"].asString();
      string node     = self_data["node"].asString();
      strings = Resources::getResourceNode(resource, node);
    }
  

  //Create array of human readable strings. New entry every "self_maxLines"
  //lines
  stringstream outputStream;
  int lineN = 0;
  for (Json::ValueIterator itr = strings.begin(); 
       itr != strings.end(); 
       itr++)
  {
    //Stored as "key" : "value", so extract these
    string key = itr.key().asString();
    Json::Value value = strings[key];
 
    //buffer key and do appropriate thing for value
    outputStream << key << self_delimiter;
    if (value.type() == Json::stringValue)
      outputStream << value.asString();
    else if (value.isNumeric())
      outputStream << value.asDouble();
    outputStream << "\n";

    lineN++;
    if ( lineN == self_maxLines )
    {
      self_displayStrings.push_back(outputStream.str());
      lineN = 0;
      outputStream.str("");
    }

  }
  //Add remaining string
  self_displayStrings.push_back( outputStream.str() );
}
示例#7
0
bool deserialize(const Json::Value& node, uint8_t& val)
{
	if (node.empty())
	{
		std::cout << "Node is empty." << std::endl;
		return false;
	}
	if (!node.isNumeric())
	{
		std::cout << "Node data type is not numeric." << std::endl;
		return false;
	}
	val = (uint8_t)node.asInt();
	return true;
}
示例#8
0
bool deserialize(const Json::Value& node, double& d)
{
	if (node.empty())
	{
		std::cout << "Node is empty." << std::endl;
		return false;
	}
	if (!node.isNumeric())
	{
		std::cout << "Node data type is not numeric." << std::endl;
		return false;
	}
	d = node.asDouble();
	return true;
}
示例#9
0
bool deserialize(const Json::Value& node, float& f)
{
	if (node.empty())
	{
		std::cout << "Node is empty." << std::endl;
		return false;
	}
	if (!node.isNumeric())
	{
		std::cout << "Node data type is not numeric." << std::endl;
		return false;
	}
	f = node.asFloat();
	return true;
}
示例#10
0
    void LuaModule::pushJsonScalarValue(const Json::Value &key,
                                        const Json::Value &val, lua_State * stack) {
        if (val.isObject() || val.isArray()) {
            throw std::runtime_error("Not a scalar value");
        }

        if (key.isString()) {
            pushKey(key, stack);
        }
        pushValue(val, stack);
        if (key.isNumeric()) {
            lua_rawseti(stack, -2, key.asInt() + 1);
        } else if (key.isString()) {
            lua_settable(stack, -3);
        }
    }
示例#11
0
ProbeAPI::PingResult::PingResult(const Json::Value& v)
{
	// Ping results:
	// "PingTime": 35,
	// "PingTime": null, (OLD)
	// "PingTime": "TimedOut", (NEW)
	// Tracert results:
	// "Ping2":"1",
	// "Ping3":"-",
	const int nDefaultVal = 9999;

	bTimeout = false;
	nTimeMs = nDefaultVal;

	if (v.isNull())
	{
		bTimeout = true;
		nTimeMs = nDefaultVal;
	}
	else if(v.isNumeric())
	{
		nTimeMs = v.asInt();
	}
	else if (v.isString())
	{
		const string sVal = v.asString();
		if (sVal == "-" || sVal == "TimedOut")
		{
			bTimeout = true;
			nTimeMs = nDefaultVal;
		}
		else if (!sVal.empty() && sVal[0] >= '0' && sVal[0] <= '9')
		{
			nTimeMs = stoi(sVal);
		}
		else
		{
			throw PException(eRetCode::ApiParsingFail) << "Failed parsing ping result: type = " << v.type() << "; value = " << v;
		}
	}
	else
	{
		throw PException(eRetCode::ApiParsingFail) << "Failed parsing ping result: type = " << v.type() << "; value = " << v;
	}
}
示例#12
0
// Programmer must free memory
Json::Value *CFG::CFG_Fetch(Json::Value *section, std::string key, 
    Json::Value *defval) {

    Json::Value *val = CFG_Fetch_Raw(section, key, defval ? 
        new Json::Value(*defval) : defval);

    if(!val)
        return defval;

    if( val->isNumeric() ) {
        if( defval ) delete defval;
        return val;
    } else if ( val->isString() ) {
        Json::Value *val2 = new Json::Value(Eval(val->asCString()));
        return val2 ? val2 : defval;
    }
    return defval;
}
std::string GlobalizationNDK::isDayLightSavingsTime(const std::string& args)
{
    if (args.empty()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::isDayLightSavingsTime: no date provided.");
        return errorInJson(UNKNOWN_ERROR, "No date is provided!");
    }

    Json::Reader reader;
    Json::Value root;
    bool parse = reader.parse(args, root);

    if (!parse) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::isDayLightSavingsTime: invalid json data: %s",
                args.c_str());
        return errorInJson(PARSING_ERROR, "Parameters not valid json format!");
    }

    Json::Value dv = root["date"];

    if (!dv.isNumeric()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::isDayLightSavingsTime: invalid date format: %d",
                dv.type());
        return errorInJson(PARSING_ERROR, "Invalid date format!");
    }

    double date = dv.asDouble();

    UErrorCode status = U_ZERO_ERROR;
    SimpleDateFormat* sdf = new SimpleDateFormat(status);
    if (!sdf) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::isDayLightSavingsTime: unable to create SimpleDateFormat instance: %d.",
                status);
        return errorInJson(UNKNOWN_ERROR, "Unable to create SimpleDateFormat instance!");
    }

    const TimeZone& tz = sdf->getTimeZone();
    bool result = tz.inDaylightTime(date, status);

    return resultInJson(result);
}
示例#14
0
 void Transform::onDeserialize( const std::string& property, const Json::Value& root )
 {
     if( property == "Position" && root.isArray() && root.size() >= 2 )
     {
         m_position = sf::Vector2f(
             (float)root[ 0u ].asDouble(),
             (float)root[ 1u ].asDouble()
         );
     }
     else if( property == "Rotation" && root.isNumeric() )
         m_rotation = (float)root.asDouble();
     else if( property == "Scale" && root.isArray() && root.size() >= 2 )
     {
         m_scale = sf::Vector2f(
             (float)root[ 0u ].asDouble(),
             (float)root[ 1u ].asDouble()
         );
     }
     else if( property == "Mode" && root.isString() )
         m_mode = Serialized::deserializeCustom< ModeType >( "Transform::ModeType", root );
     else
         Component::onDeserialize( property, root );
 }
示例#15
0
文件: JsonUtils.cpp 项目: onze/Steel
    Ogre::Vector3 JsonUtils::asVector3(Json::Value const &value, const Ogre::Vector3 &defaultValue)
    {
        if(value.isString())
        {
            auto const &s = value.asString();

            if(Ogre::StringConverter::isNumber(s))
            {
                float f = Ogre::StringConverter::parseReal(s);
                return Ogre::Vector3(f, f, f);
            }
            else
            {
                return Ogre::StringConverter::parseVector3(s);
            }
        }
        else if(value.isNumeric())
        {
            float f = value.asFloat();
            return Ogre::Vector3(f, f, f);
        }

        return defaultValue;
    }
示例#16
0
Json::Value mesos_http::get_task_labels(const std::string& task_id)
{
	std::ostringstream os;
	CURLcode res = get_data(make_uri("/master/tasks"), os);

	Json::Value labels;
	if(res != CURLE_OK)
	{
		g_logger.log(curl_easy_strerror(res), sinsp_logger::SEV_ERROR);
		return labels;
	}

	try
	{
		Json::Value root;
		Json::Reader reader;
		if(reader.parse(os.str(), root, false))
		{
			Json::Value tasks = root["tasks"];
			if(!tasks.isNull())
			{
				for(const auto& task : tasks)
				{
					Json::Value id = task["id"];
					if(!id.isNull() && id.isString() && id.asString() == task_id)
					{
						Json::Value statuses = task["statuses"];
						if(!statuses.isNull())
						{
							double tstamp = 0.0;
							for(const auto& status : statuses)
							{
								// only task with most recent status
								// "TASK_RUNNING" considered
								Json::Value ts = status["timestamp"];
								if(!ts.isNull() && ts.isNumeric() && ts.asDouble() > tstamp)
								{
									Json::Value st = status["state"];
									if(!st.isNull() && st.isString())
									{
										if(st.asString() == "TASK_RUNNING")
										{
											labels = task["labels"];
											tstamp = ts.asDouble();
										}
										else
										{
											labels.clear();
										}
									}
								}
							}
							if(!labels.empty()) // currently running task found
							{
								return labels;
							}
						}
					}
				}
			}
		}
		else
		{
			g_logger.log("Error parsing tasks.\nJSON:\n---\n" + os.str() + "\n---", sinsp_logger::SEV_ERROR);
		}
	}
	catch(std::exception& ex)
	{
		g_logger.log(std::string("Error parsing tasks:") + ex.what(), sinsp_logger::SEV_ERROR);
	}

	return labels;
}
float ParserActionParameters::parseFloat(Json::Value temp_info){
	if(!temp_info.isNull() && temp_info.isNumeric()){
		return temp_info.asFloat();
	}
	return 0;
}
std::string GlobalizationNDK::numberToString(const std::string& args)
{
    if (args.empty()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: no arguments provided!");
        return errorInJson(UNKNOWN_ERROR, "No arguments provided!");
    }

    Json::Reader reader;
    Json::Value root;
    bool parse = reader.parse(args, root);

    if (!parse) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: invalid json data: %s",
                args.c_str());
        return errorInJson(PARSING_ERROR, "Invalid json data!");
    }

    Json::Value nv = root["number"];
    if (nv.isNull()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: no number provided!");
        return errorInJson(FORMATTING_ERROR, "No number provided!");
    }

    if (!nv.isNumeric()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: invalid number type: %d!",
                nv.type());
        return errorInJson(FORMATTING_ERROR, "Invalid number type!");
    }

    // This is the default value when no options provided.
    ENumberType type = kNumberDecimal;

    Json::Value options = root["options"];
    std::string error;
    if (!handleNumberOptions(options, type, error))
        return errorInJson(PARSING_ERROR, error);

    UErrorCode status = U_ZERO_ERROR;
    NumberFormat* nf;
    switch (type) {
    case kNumberDecimal:
    default:
        nf = NumberFormat::createInstance(status);
        break;
    case kNumberCurrency:
        nf = NumberFormat::createCurrencyInstance(status);
        break;
    case kNumberPercent:
        nf = NumberFormat::createPercentInstance(status);
        break;
    }

    if (!nf) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::numberToString: failed to create NumberFormat instance for type %d: %d",
                status, type);
        return errorInJson(UNKNOWN_ERROR, "Failed to create NumberFormat instance!");
    }
    std::auto_ptr<NumberFormat> deleter(nf);

    UnicodeString result;
    nf->format(nv.asDouble(), result);
    std::string utf8;
    result.toUTF8String(utf8);

    return resultInJson(utf8);
}
示例#19
0
ExpressionType parseExpressionType(const Json::Value &value) {
    if (value.isString()) return getExpressionMap()[value.asString()];
    else if (value.isNumeric()) return (ExpressionType) value.asInt();
    else throw std::runtime_error("Expression '" + value.asString() + "' could not be parsed");
}
示例#20
0
PredicateType::type parsePredicateType(const Json::Value &value) {
    if (value.isString()) return getPredicateMap()[value.asString()];
    else if (value.isNumeric()) return (PredicateType::type) value.asInt();
    else throw std::runtime_error("Predicate '" + value.asString() + "' could not be parsed");
}