给一个POCO中C++Parse解析复杂JSON格式数据示例
时间: 2024-03-08 19:47:27 浏览: 14
下面是一个使用 Poco C++ 库中的 JSON 解析器来解析复杂的 JSON 格式数据的示例代码:
```
#include <iostream>
#include <sstream>
#include <Poco/JSON/Parser.h>
#include <Poco/JSON/Array.h>
#include <Poco/JSON/Object.h>
using namespace Poco::JSON;
int main()
{
std::string jsonString = R"({
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-555-1234"
},
{
"type": "work",
"number": "555-555-5678"
}
]
})";
Parser parser;
Var result = parser.parse(jsonString);
Object::Ptr object = result.extract<Object::Ptr>();
std::string name = object->getValue<std::string>("name");
int age = object->getValue<int>("age");
Object::Ptr address = object->getObject("address");
std::string street = address->getValue<std::string>("street");
std::string city = address->getValue<std::string>("city");
std::string state = address->getValue<std::string>("state");
std::string zip = address->getValue<std::string>("zip");
Array::Ptr phoneNumbers = object->getArray("phoneNumbers");
for (Array::ConstIterator it = phoneNumbers->begin(); it != phoneNumbers->end(); ++it)
{
Object::Ptr phoneNumber = it->extract<Object::Ptr>();
std::string type = phoneNumber->getValue<std::string>("type");
std::string number = phoneNumber->getValue<std::string>("number");
std::cout << "Phone number (" << type << "): " << number << std::endl;
}
return 0;
}
```
在这个例子中,我们首先定义了一个包含复杂 JSON 格式数据的字符串 `jsonString`。然后,我们使用 `Parser` 类来解析这个字符串,并将解析结果存储在 `Var` 类型的变量 `result` 中。
接下来,我们使用 `getValue()` 函数从 `Object` 类型的变量 `object` 中获取 name 和 age 字段的值,并将它们存储在 `name` 和 `age` 变量中。我们还使用 `getObject()` 函数获取 address 对象,并使用 `getValue()` 函数从中获取 street、city、state 和 zip 字段的值。
最后,我们使用 `getArray()` 函数获取 phoneNumbers 数组,并使用 `Array::ConstIterator` 迭代器遍历数组中的每个对象。对于每个对象,我们使用 `getValue()` 函数获取 type 和 number 字段的值,并将它们打印到控制台上。
需要注意的是,以上代码仅为示例代码,实际应用中应该考虑错误处理和异常情况。