zoukankan      html  css  js  c++  java
  • jsoncpp用法简述

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

    Jsoncpp提供的接口中有3个核心类:ReaderWriterValue。

    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"
        }

  • 相关阅读:
    Eureka相关相关接口和代码位置
    Zookeeper(4)---ZK集群部署和选举
    Zookeeper(3)---java客户端的使用
    Zookeeper(2)---节点属性、监听和权限
    玩转百度地图API(地图,坐标,标记,添加控件,2D图,混合图,智能搜索,地址解析器,信息窗口)
    HTML+CSS系列:CSS选择器(标签、ID、类、通配符、后代、子元素、并集、伪类)
    Git系列:常用命令
    Linux系列:快捷键、目录结构、用户目录
    mybatis-plus系统化学习之更新-AR-主键-service
    mybatis-plus系统化学习之查询专题
  • 原文地址:https://www.cnblogs.com/edgarli/p/3047687.html
Copyright © 2011-2022 走看看