c/c++ jsoncpp的基本使用

一、概述

  jsoncpp官网

  作用:在c++中可以方便的组装及解析json格式的数据。

二、代码示例

void MyJsonCpp::toJsonStr() {
    Json::Value jsonValue;
    jsonValue["username"] = "luoluoyang";
    jsonValue["password"] = "123456";
    jsonValue["age"] = 6;
    jsonValue["sex"] = "man";
    cout << "toJsonStr=" << jsonValue.toStyledString().c_str() << endl;
}

void MyJsonCpp::parseJson() {
    //字符串
    string str = "{\"name\":\"shuiyixin\",\"age\":21,\"sex\":\"man\"}";
    //声明类的对象
    Json::Reader reader;
    Json::Value root;
    //从字符串读取数据
    if (reader.parse(str, root)) {
        string name = root["name"].asString();
        int age = root["age"].asInt();
        string sex = root["sex"].asString();
        cout << root.toStyledString() << endl;
    }
}

void MyJsonCpp::writeFileJson() {
    //根节点
    Json::Value root;
    root["name"] = Json::Value("LOL");
    root["age"] = Json::Value("18");
    root["sex"] = Json::Value("male");
    //子节点
    Json::Value bro;
    bro["friend_name"] = "德玛西亚";
    bro["friend_age"] = Json::Value("18");
    bro["friend_sex"] = "";
    root["friend"] = Json::Value(bro);
    cout << root.toStyledString() << endl;

}

 

posted on 2024-07-23 15:56  飘杨......  阅读(77)  评论(0)    收藏  举报