As we have already know, we use following code for parsing json data
std::string jsonString = "{\"aa\":\"bb\"}";
Poco::JSON::Parser parser;
Poco::Dynamic::Var result;
result = parser.parse(jsonString);
Poco::JSON::Object::Ptr pObj = result.extract<Poco::JSON::Object::Ptr>();
... // goes with pObj
We know "{\"aa\":\"bb\"}" is json object, so we use result.extract
and following code for parsing json array data
std::string jsonString = "[{\"aa\":\"bb\"}, {\"cc\":\"dd\"}]";
Poco::JSON::Parser parser;
Poco::Dynamic::Var result;
result = parser.parse(jsonString);
Poco::JSON::Array::Ptr pArr = result.extract<Poco::JSON::Array::Ptr>();
... // goes with pArr
we know "[{\"aa\":\"bb\"}, {\"cc\":\"dd\"}]", so we use result.extract
So, my first thought is:
...
try {
Poco::JSON::Object::Ptr pObj = result.extract<Poco::JSON::Object::Ptr>(); // this does be a json object
} catch (...) {}
try {
Poco::JSON::Array::Ptr pArr = result.extract<Poco::JSON::Array::Ptr>(); // this does be a json array
} catch (...) {}
...
Then, Using code above with exception catch, I can distinguish Object from Array.
So, is there any way that solving this kind question without exception catch?
Use C++'s type info to solve this problem
std::string jsonString = "[{\"aa\":\"bb\"}, {\"cc\":\"dd\"}]";
// or std::string jsonString = "{{\"aa\":\"bb\"}, {\"cc\":\"dd\"}}";
try {
result = parser.parse(jsonString);
} catch (Poco::SyntaxException & e) {
std::cout << "This is not a valid json data" << std::endl;
return;
}
Poco::JSON::Array::Ptr p;
if (typeid(p) == result.type()) {
std::cout << "This is a arry" << std::endl;
} else {
std::cout << "This is a object" << std::endl;
}