[json] poco c++解析json数组

解析json数组,搜了还就没好到,翻了翻官方文档,自己写了个例子。内容挺简单的,不多做介绍了,直接把代码贴上来。
数据数组

[
    {
     
      "phone": 15612345678,
      "name": "XiaoMing",
      "age": 18,
      "address": ["Beijing", "Shanghai", "Shenzhen"]
    },
    {
     
      "phone": 18912345678,
      "name": "XiaoQiang",
      "age": 17,
      "address": ["Xi'an", "Nanjing", "Chengdu"]
    }
  ]

C++代码

void testJson2St() {
     
    string src =
        "[{\"phone\":15612345678,\"name\":\"XiaoMing\",\"age\":18,\"address\":["
        "\"Beijing\",\"Shanghai\",\"Shenzhen\"]},{\"phone\":18912345678,"
        "\"name\":\"XiaoQiang\",\"age\":17,\"address\":[\"Xi'an\",\"Nanjing\","
        "\"Chengdu\"]}]";

    Poco::JSON::Parser parser;
    Poco::Dynamic::Var json = parser.parse(src);
    //拿到数组指针
    Poco::JSON::Array::Ptr array = json.extract<Poco::JSON::Array::Ptr>();
    cout << "array.size=" << array->size() << endl;
    // 遍历数组
    for (int i = 0; i < array->size(); i++) {
     
        // 拿到第i个元素
        Poco::Dynamic::Var ele = array->get(i);
        Poco::JSON::Object theObj = *ele.extract<Poco::JSON::Object::Ptr>();

        // 获取基本类型元素
        Poco::Dynamic::Var phone = theObj.get("phone");
        Poco::Dynamic::Var name = theObj.get("name");
        Poco::Dynamic::Var age = theObj.get("age");
        std::cout << age.convert<int>() << std::endl;
        std::cout << name.toString() << std::endl;
        std::cout << phone.toString() << std::endl;

        // 获取数组类型元素
        Poco::Dynamic::Var address = theObj.get("address");
        Poco::JSON::Array::Ptr addr_arry =
            address.extract<Poco::JSON::Array::Ptr>();
        cout << "addr_arry.size=" << addr_arry->size() << endl;
        // 遍历数组
        for (int i = 0; i < addr_arry->size(); i++) {
     
            // 拿到第i个元素
            Poco::Dynamic::Var addr = addr_arry->get(i);
            std::cout << addr.toString() << std::endl;
        }
        cout << "------------" << endl;
    }
}

你可能感兴趣的:(数据分析,c++,json,poco)