jsoncpp使用简介

Jsoncpp是一个使用C++语言实现的面向对象的json库。

Jsoncpp提供的接口中有3个核心类:Reader、Writer、Value。

Reader类负责从字符串或者输入流中加载JSON文档,并进行解析,生成代表JSON文档的Value对象。

Writer类负责将内存中的Value对象转换成JSON文档,可输出到文件或者是字符串中。

Value类的对象代表一个JSON值,既可以代表一个文档,也可以代表文档中一个值。

一个JSON文档的大致过程如下:

//准备Json源数据,如读取文档:Std::string strdoc = readFromFile(… );

。。。

//生命顶级Value对象

Json::Value root;

//声明Reader对象

Json::Reader _reader;

//解析json文档
_reader.paser(strdoc, root);

Json::ValueType有8种,以下是定义。 enum Json::ValueType
Enumerator:
nullValue    ‘null’ value
intValue     signed integer value
uintValue    unsigned integer value
realValue    double value
stringValue    UTF-8 string value.
booleanValue   bool value
arrayValue    array value (ordered list)
objectValue    object value (collection of name/value pairs).

static void printValueTree( FILE *fout, Json::Value &value, const std::string &path = "." ) 
{ 
switch ( value.type() ) 
{ 
case Json::nullValue:    
    fprintf( fout, "%s=null\n", path.c_str() );
    break;
case Json::intValue:
    fprintf( fout, "%s=%d\n", path.c_str(), value.asInt() );
    break;
case Json::uintValue:
    fprintf( fout, "%s=%u\n", path.c_str(), value.asUInt() );
    break;
case Json::realValue:
    fprintf( fout, "%s=%.16g\n", path.c_str(), value.asDouble() );
    break;
case Json::stringValue:
    fprintf( fout, "%s=\"%s\"\n", path.c_str(), value.asString().c_str() );
    break;
case Json::booleanValue:
    fprintf( fout, "%s=%s\n", path.c_str(), value.asBool() ? "true" : "false" );
    break;
case Json::arrayValue:
{
    fprintf( fout, "%s=[]\n", path.c_str() );
    int size = value.size();
    for ( int index =0; index < size; ++index )
    {
        static char buffer[16];
        sprintf( buffer, "[%d]", index );
        printValueTree( fout, value[index], path + buffer );
    }
}
break;
case Json::objectValue:
{
    fprintf( fout, "%s={}\n", path.c_str() );
    Json::Value::Members members( value.getMemberNames() );
    std::sort( members.begin(), members.end() );
    std::string suffix = *(path.end()-1) == '.' ? "" : ".";
    for ( Json::Value::Members::iterator it = members.begin(); it != members.end();         ++it )
    {
        const std::string &name = *it;
        printValueTree( fout, value[name], path + suffix + name );
    }
}
break;
default:
    break; 
} 
}

1) Json::Reader 是用于读取Json对象的值。
用法:

Json::Value reader_object;
Json::Reader reader;
const char* reader_document = "{"path" : "/home/test.mp3","size" : 4000}";
if (!reader.parse(reader_document, reader_object))
    return 0;
std::cout << reader_object["path"] << std::endl;
std::cout << reader_object["size"] << std::endl;
结果:
"/home/test.mp3"
4000 

2) 增加子节点

Json::Value root;

Json::Value leaf;

...

  root[“leaf_node”] = leaf;

3) 值为数组的,通过对同一key逐个append方式追加:

root["key_array"].append("the string");  //元素值类型为字符串

root["key_array"].append(20);                  //元素值类型同时可为int等等

4) 解析数组值

JArray = root["key_array"];
for ( unsigned int i = 0; i < JArray.size(); i++ )
{
    cout << "JSON array values: " << JArray[i].asString() << endl;
}

5) 注意操作符[]的定义:

Value & Json::Value::operator[] ( const StaticString & key )

Access an object value by name, create a null member if it does not exist.
因此但凡使用[]或者通过get()间接使用[]的,若原来元素不存在,都将增加一个value为null的新元素。

事先判断某名称的元素是否存在可以使用 isMember():

if(infoRoot.isObject() && infoRoot.isMember(“error”))

  

二. 通过使用Writer将Value转换为JSON文档(string):

1) Json::FastWriter用来快速输出Json对象的值,即。

用法:
  Json::FastWriter writer;
  std::cout << writer.write(json_media)<< std::endl;
结果:
{"isArray":["test1","test2"],"isBoolean":true,"isDouble":0.25,"size":4000,"isObject": {},"path":"/home/mp3/test.mp3"}

2) Json::StyledWriter用来格式化输出Json对象的值。

用法:
  Json::StyledWriter writer;
  std::cout << writer.write(json_media) << std::endl;
结果:
{
   "isArray" : [ "test1", "test2" ],
   "isBoolean" : true,
   "isDouble" : 0.24,
   "size" : 4000,
   "isObject" : {},
   "path" : "/home/mp3/test.mp3"
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值