您现在的位置是:网站首页 > 其他实战 > jsoncpp快速使用

简介本文介绍jsoncpp快速使用,感兴趣的朋友可以参考一下。

jsoncpp 主要包含三种类型的 class:Value、Reader、Writer。jsoncpp 中所有对象、类名都在 namespace Json 中,包含 json.h 即可。

Json::Value 只能处理 ANSI 类型的字符串,如果 C++ 程序是用 Unicode 编码的,最好加一个 Adapt 类来适配。

从字符串中读取

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    //字符串
    const char* str = "{\"praenomen\":\"Gaius\",\"nomen\":\"Julius\",\"cognomen\":\"Caezar\",\"born\":-100,\"died\":-44}";

    Json::Reader reader;
    Json::Value root;
 
    //从字符串中读取数据
    if (reader.parse(str, root))
    {
         string praenomen = root["praenomen"].asString();
         string nomen = root["nomen"].asString();
         string cognomen = root["cognomen"].asString();
         int born = root["born"].asInt();
         int died = root["died"].asInt();
         cout << praenomen + " " + nomen + " " + cognomen << " was born in year " << born << ", died in year " << died << endl;
    }
    return 0;
}

从文件中读取

// 从文件中读取
Json::Reader reader;
Json::Value root;

ifstream is;
is.open("PersonalInfo.json", ios::binary);
if (reader.parse(is, root))
{
     // 读取根节点信息
     string name = root["name"].asString();
     int age = root["age"].asInt();
     bool sex_is_male = root["sex_is_male"].asBool();
     cout << "My name is " << name << endl;
     cout << "I'm " << age << " years old" << endl;
     cout << "I'm a " << (sex_is_male ? "man" : "woman") << endl;

     // 读取子节点信息
     string partner_name = root["partner"]["partner_name"].asString();
     int partner_age = root["partner"]["partner_age"].asInt();
     bool partner_sex_is_male = root["partner"]["partner_sex_is_male"].asBool();
     cout << "My partner's name is " << partner_name << endl;
     cout << (partner_sex_is_male ? "he" : "she") << " is " << partner_age << " years old" << endl;

     // 读取数组信息
     cout << "Here's my achievements:" << endl;
     for (int i = 0; i < root["achievement"].size(); i++)
     {
         string ach = root["achievement"][i].asString();
         cout << ach << '\t';
     }
     cout << endl;
     cout << "Reading Complete!" << endl;
}

写入文件

// 根节点
Json::Value root;
root["name"] = Json::Value("Tsybius");
root["age"] = Json::Value(23);
root["sex_is_male"] = Json::Value(true);

// 子节点
Json::Value partner;
partner["partner_name"] = Json::Value("Galatea");
partner["partner_age"] = Json::Value(21);
partner["partner_sex_is_male"] = Json::Value(false);

// 子节点挂到根节点上
root["partner"] = Json::Value(partner);

// 数组形式
root["achievement"].append("ach1");
root["achievement"].append("ach2");
root["achievement"].append("ach3");

// 直接输出
cout << "FastWriter:" << endl;
Json::FastWriter fw;
cout << fw.write(root) << endl << endl;

// 缩进输出
cout << "StyledWriter:" << endl;
Json::StyledWriter sw;
cout << sw.write(root) << endl << endl;

// 输出到文件
ofstream os;
os.open("PersonalInfo.json");
os << sw.write(root);
os.close();


更多为你推荐