jsoncpp基础

来源:互联网 发布:网络借贷平台有哪些 编辑:程序博客网 时间:2024/06/10 21:37

jsoncpp是常用的C++语言JSON解析库,它主要包含三个class:Value、Reader、Writer。

下面根据自己查到的资料等总结其用法(使用时 #include “json/json.h”):
1.Value
因为是表示各种类型的对象,因此自然就是最基本、最重要的class。下面用简单的代码看看它怎么用,真的很方便的:

Json::Value temp;                      // 临时对象temptemp["name"] = Json::Value("Alieen");  //name是Alieentemp["age"] = Json::Value(18);         //age是18

root表示整个json对象

Json::Value root;               // 表示整个 json 对象root["str"] = Json::Value("value_string");         // 新建一个 Key(名为str),赋予字符串值:"value_string"。root["num"] = Json::Value(12345);            // 新建一个 Key(名为num),赋予数值:12345。root["double"] = Json::Value(12.345);            // 新建一个 Key(名为double),赋予 double 值:12.345。root["boolean"] = Json::Value(false);             // 新建一个 Key(名为boolean),赋予bool值:false。root["key_object"] = temp;                          // 新建一个 Key(名为key_object),赋予 Json::Value temp 对象值。root["key_array"].append("array_string");             // 新建一个 Key(名为key_array),类型为数组,对第一个元素赋值为字符串:"array_string"。root["key_array"].append(1234);                           //为数组 key_array 赋值,对第二个元素赋值为:1234。//注:数组中可以有不同类型的值**Json::ValueType type = root.type();                       // 获得 root 的类型,此处为 objectValue 类型。

2.Reader
将json文件流或字符串解析到Json::Value, 主要函数有Parse.

 Json::Reader reader; Json::Value json_object; const char* json_document = "{\"age\" : 18,\"name\" : \"Alieen\"}"; if (!reader.parse(json_document, json_object))    return 0; std::cout << json_object["name"] << std::endl; std::cout << json_object["age"]  << std::endl;

输出结果(待检验):

Alieen18

3.Writer
与Json::Reader相反,是将Json::Value转化成字符串流。
它的两个子类:
①Json::FastWriter(不带格式json)
②Json::StyleWriter(带格式json)
Jsoncpp 的 Json::Writer 类是一个纯虚类,不能直接使用。使用 Json::Writer 的子类:Json::FastWriter、Json::StyledWriter、Json::StyledStreamWriter。

Json::FastWriter fast_writer;std::cout << fast_writer.write(root) << std::endl;

输出:

{"key_array":["str",1234],"key_boolean":false,"key_double":12.3450,"key_number":12345,"key_object":{"age":18,"name":"Alieen"},"key_string":"value_string"}

用 Json::StyledWriter 是格式化后的 json,下面我们来看看 Json::StyledWriter 是怎样格式化的。

Json::StyledWriter styled_writer;std::cout << styled_writer.write(root) << std::endl;

输出:

{   "key_array" : [ "str", 1234 ],   "key_boolean" : false,   "key_double" : 12.3450,   "key_number" : 12345,   "key_object" : {      "age" : 18,      "name" : "Alieen"   },   "key_string" : "value_string"}

(好多blog因为copy&paste都有这句话:“ Json::Value 只能处理 ANSI 类型的字符串,如果 C++ 程序是用 Unicode 编码的,最好加一个 Adapt 类来适配。”之前写别的程序遇到过这种问题,也试着查过这个问题,但是未果,暂且随它去吧,有bug了再说…)


下面是一些实例:(参考)
1.文件读写

#include <iostream>#include <fstream>#include "json.h"static bool write_jscon( const char * json_file, const Json:: Value & val){           if ( json_file == NULL)                    return false;          std:: ofstream out_json( json_file);           if (!out_json)                    return false;          Json:: StyledStreamWriter writer;          writer.write(out_json, val);          out_json.close();           return true;}static bool read_json(const char *json_file , Json::Value &val ){          std:: ifstream in_file( json_file, std:: ios::binary);           if (! json_file)                    return false;           if (!Json:: Reader().parse(in_file, val))          {                   in_file.close();                    return false;          }          in_file.close();           return true;}

2.从字符串中读取JSON

#include <iostream #include "json/json.h" using namespace std;int main(){    //字符串    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;}

3.从文件中读取json
文件PersonalInfo.json(一个存储了JSON格式字符串的文件)

{    "name":"Tsybius",    "age":23,    "sex_is_male":true,    "partner":    {        "partner_name":"Galatea",        "partner_age":21,        "partner_sex_is_male":false    },    "achievement":["ach1","ach2","ach3"]}

a.cpp

#include <iostream>#include <fstream>#include "json/json.h"using namespace std;int main(){    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;    }    is.close();    return 0;}

4.将信息保存为json格式
a.cpp

#include <iostream>#include <fstream>#include "json/json.h"using namespace std;int main(){    //根节点    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");    os << sw.write(root);    os.close();    return 0;}

生成的文件PersonalInfo.json

{   "achievement" : [ "ach1", "ach2", "ach3" ],   "age" : 23,   "name" : "Tsybius",   "partner" : {      "partner_age" : 21,      "partner_name" : "Galatea",      "partner_sex_is_male" : false   },   "sex_is_male" : true}

代码来源:
http://my.oschina.net/Tsybius2014/blog/289527

0 0
原创粉丝点击