加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

jsoncpp使用简介

发布时间:2020-12-16 19:37:07 所属栏目:百科 来源:网络整理
导读:Jsoncpp是一个使用C++语言实现的面向对象的json库。 Jsoncpp提供的接口中有3个核心类:Reader、Writer、Value。 Reader类负责从字符串或者输入流中加载JSON文档,并进行解析,生成代表JSON文档的Value对象。 Writer类负责将内存中的Value对象转换成JSON文档

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=nulln",path.c_str() );
    break;
case Json::intValue:
    fprintf( fout,"%s=%dn",path.c_str(),value.asInt() );
    break;
case Json::uintValue:
    fprintf( fout,"%s=%un",value.asUInt() );
    break;
case Json::realValue:
    fprintf( fout,"%s=%.16gn",value.asDouble() );
    break;
case Json::stringValue:
    fprintf( fout,"%s="%s"n",value.asString().c_str() );
    break;
case Json::booleanValue:
    fprintf( fout,"%s=%sn",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"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读