Implemented Value::GetType().

This commit is contained in:
Gunnar Beutner 2013-02-15 14:39:26 +01:00
parent d13017ef60
commit a022be9de2
2 changed files with 45 additions and 17 deletions

View File

@ -109,24 +109,27 @@ String Value::Serialize(void) const
*/ */
cJSON *Value::ToJson(void) const cJSON *Value::ToJson(void) const
{ {
if (m_Value.type() == typeid(long)) { switch (GetType()) {
return cJSON_CreateNumber(boost::get<long>(m_Value)); case ValueNumber:
} else if (m_Value.type() == typeid(double)) { return cJSON_CreateNumber(boost::get<double>(m_Value));
return cJSON_CreateNumber(boost::get<double>(m_Value));
} else if (m_Value.type() == typeid(String)) { case ValueString:
return cJSON_CreateString(boost::get<String>(m_Value).CStr()); return cJSON_CreateString(boost::get<String>(m_Value).CStr());
} else if (m_Value.type() == typeid(Object::Ptr)) {
if (IsObjectType<Dictionary>()) { case ValueObject:
Dictionary::Ptr dictionary = *this; if (IsObjectType<Dictionary>()) {
return dictionary->ToJson(); Dictionary::Ptr dictionary = *this;
} else { return dictionary->ToJson();
Logger::Write(LogDebug, "base", "Ignoring unknown object while converting variant to JSON."); } else {
Logger::Write(LogDebug, "base", "Ignoring unknown object while converting variant to JSON.");
return cJSON_CreateNull();
}
case ValueEmpty:
return cJSON_CreateNull(); return cJSON_CreateNull();
}
} else if (m_Value.type() == typeid(boost::blank)) { default:
return cJSON_CreateNull(); BOOST_THROW_EXCEPTION(runtime_error("Invalid variant type."));
} else {
BOOST_THROW_EXCEPTION(runtime_error("Invalid variant type."));
} }
} }
@ -148,3 +151,13 @@ Value Value::Deserialize(const String& jsonString)
return value; return value;
} }
/**
* Returns the type of the value.
*
* @returns The type.
*/
ValueType Value::GetType(void) const
{
return static_cast<ValueType>(m_Value.which());
}

View File

@ -25,6 +25,19 @@ struct cJSON;
namespace icinga namespace icinga
{ {
/**
* The type of a Value.
*
* @ingroup base
*/
enum ValueType
{
ValueEmpty = 0,
ValueNumber = 1,
ValueString = 2,
ValueObject = 3
};
/** /**
* A type that can hold an arbitrary value. * A type that can hold an arbitrary value.
* *
@ -127,6 +140,8 @@ public:
String Serialize(void) const; String Serialize(void) const;
static Value Deserialize(const String& jsonString); static Value Deserialize(const String& jsonString);
ValueType GetType(void) const;
private: private:
mutable boost::variant<boost::blank, double, String, Object::Ptr> m_Value; mutable boost::variant<boost::blank, double, String, Object::Ptr> m_Value;
}; };