boost中json库的用法

·

boost在最新的1.75版本加入了json库,下面是该库的使用小例。

#include <stdio.h>
#include <boost/json.hpp>
#include <iostream>


void test1(std::string &str)
{
    boost::json::object obj;

    obj["1"] = { {"v1","abc"},
                   {"v2","def"} ,
                   {"v3","ghi"},
                   {"v4",1234},
                   {"v5", 5678}
    };
    
    obj["2"] = "test";

    str = boost::json::serialize(obj);

    
}

void main(int argc, char* argv[])
{
    std::string str;
    test1(str);
    std::cout << str << std::endl;
    //解析字符串
    boost::json::value val = boost::json::parse(str);

    if (val.is_object())
    {
        for (auto obj : val.as_object())
        {
            if (obj.key() == "1")
            {
                if (obj.value().is_object() == false)
                {
                    break;
                }
                for (auto elm : obj.value().as_object())
                {
                    if (elm.key() == "v1")
                    {
                        if (elm.value().is_string() == false)
                        {
                            break;
                        }
                        std::cout << elm.value() << std::endl;
                    }
                    if (elm.key() == "v2")
                    {
                        if (elm.value().is_string() == false)
                        {
                            break;
                        }
                        std::cout << elm.value() << std::endl;
                    }
                    if (elm.key() == "v3")
                    {
                        if (elm.value().is_string() == false)
                        {
                            break;
                        }
                        std::cout << elm.value() << std::endl;
                    }
                    if (elm.key() == "v4")
                    {
                        if (elm.value().is_number() == false)
                        {
                            break;
                        }
                        std::cout << elm.value() << std::endl;
                    }
                    if (elm.key() == "v5")
                    {
                        if (elm.value().is_number() == false)
                        {
                            break;
                        }
                        std::cout << elm.value() << std::endl;
                    }
                }
            }
            if (obj.key() == "2")
            {
                if (obj.value().is_string() == false)
                {
                    break;
                }
                std::cout << obj.value() << std::endl;
            }
        }
    }
    getchar();
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注