JSON函数表2
[class] Json::Reader
    [public]
    [将字符串或者输入流转换为JSON的Value对象]
        bool parse( const std::string &document, Value &root, bool collectComments = true );
        bool parse( const char *beginDoc, const char *endDoc, Value &root,bool collectComments = true );        
        bool parse( std::istream &is,Value &root,bool collectComments = true ); // 从文件流中读取
        // ture success ; false error
        [获取满足相应条件的Value]
        std::string getFormatedErrorMessages() const;//返回成员命名的关键如果它存在,否则defaultValue
[class] Json::Value
[注意] Json::Value 只能处理 ANSI 类型的字符串,如果 C++ 程序是用 Unicode 编码的,最好加一个 Adapt 类来适配
[注意] 要取下标为 0 的value值, 只能通过 int i=0;value[i]; 不能是 value[0];
    [public]
    [获取满足相应条件的Value]
        Value get( Uint index, const Value &defaultValue ) const;
        Value get( const char *key, const Value &defaultValue) const;   //查找是否存在 索引key ,存在则返回其对应的 :value
        Value get( const std::string &key, const Value &defaultValue ) const;
        例如:
            Json::root["one"] = 456;
            Json::Value root04 = root.get("one", root);
            cout << root04.asUInt() << endl; //456
    [Value转基本格式]
        Int asInt() const;
        UInt asUInt() const;  //能不转有符号的int
        Int64 asInt64() const;
        LargestInt asLargesInt() const;
        LargestUInt asLargestUInt() const;
        float asFloat() const;
        double asDouble() const;
        bool asBool() const;
        std::string asString() const;
        const char* asCString() const;
        std::string toStyledString() const;  // 可以把整个 value 转为 string 格式
    [判断Value格式]
        bool isNull() const;
        bool isBool() const;
        bool isDouble() const;
        bool isInt() const;
        bool isString() const;
        bool isArrar() const;
        bool isObject() const;
        bool isMember (const char *key) const  //Return true if the object has a member named key.
        bool isMember (const std::string &key) const  //Return true if the object has a member named key.
     [相同类型的比较、交换、类型的获取]
        int compare( const Value &other );  //比较两个 Value
        void swap(Value &other);  //交换两个 Value 的内容
        ValueType type()const;    //Value 的格式
    [其他功能]
        ArrayIndex size() const;  //Number of values in array or object  //typedef unsigned int Json::ArrayIndex        
        Value& append(const Value &value) //append value to < array > at the end;
        void clear();   //remove all object members and array elements
        void resize(ArrayIndex index); //调整array元素的个数,其他格式无法使用
        void empty() const;   //Number of values in array or object
        Value removeMember(const char* key); //Remove and return the named member
        Value removeMember(const std::string &key); //Same as removeMember(const char*).
    [勾造函数]
         Value (ValueType type=nullValue) Create a default Value of the given type.
        Value (Int value)
        Value (UInt value)
        Value (Int64 value)
        Value (UInt64 value)
        Value (double value)
        Value (const char *value)
        Value (const char *beginValue, const char *endValue)
        Value (const StaticString &value) Constructs a value from a static string.         
        Value (const std::string &value)
        Value (bool value)
        Value (const Value &other)    
    [迭代器] Json::Value::const_iterator
        const_iterator     begin () const
        const_iterator     end () const
        iterator     begin ()
        iterator     end ()
        //这个迭代器不要使用 != == 进行比较
    [操作符比较]
        bool     operator< (const Value &other) const  //类型相等 -> 元素个数相等 -> 比较地址
        bool     operator<= (const Value &other) const //
        bool     operator>= (const Value &other) const //
        bool     operator> (const Value &other) const  //
        bool     operator== (const Value &other) const //类型不相等返回 0 ,内容一致返回 1
            例: char arr[4] = {'1','2','3','\0'}; string str = "123";
                root["one"] == "123";
                root["one"] == str;
                root["one"] == arr;
                root["one"].asString() == arr;
                root["one"].asString() == str;
                root["one"].asString().c_str() == str.c_str();  //error                
        bool     operator!= (const Value &other) const //类型不相等返回 1 ,内容一致返回 0
        比较类型,类型相等->比较元素个数,个数相等->比较元素值
(2) 数组访问
Json::Value //格式如下
[["key1":value1],["key2":value2]]
Json::Value::const_iterator iter;  //迭代器
for(iter = input.begin(); iter != input.end(); iter++)
Json::Value::Members member=(*iter).getMemberNames();
*(member.begin());          // 输出 key1,key2
(*iter)[*(member.begin())];     //输出 value1,value2
[class] Json::FastWriter
[public]
        void     enableYAMLCompatibility ()                  //转格式时,是否在 :后面加一空格
        virtual std::string     write (const Value &root) //把 Value 转为 std::string,不格式化
[class] Json::StyledWriter
是格式化后的json
不支持utf-8格式的输出,需要自己调用writer之后,用iconv转化成utf-8字符串 //见 iconv 文件
[class] Json::Writer
继承 FastWriter StyledWriter, 它是一个虚类
[type]
enum ValueType
   {
      nullValue = 0, ///< '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).
   };
----------------------------------------------------------------------------------------------------
1、相关概念总结
(1)解析json的方法
Json::Value json; //表示一个json格式的对象
Json::Reader reader; //json解析
reader.parse(json_buf/*json格式的字符串*/,json,false); //解析出json放到json中
jsoncpp库中的Reader类用来将字串或者流载入解析器。后期可以用Reader里面的解析方法把Json字串解码为C++认识的数据。可以用 Json::Reader来声明一个Reader实例。Reader中最常用的就是一个parse方法,该方法用来将载入的json字串解析为C++格式的数据。
(2) 数组访问
Json::Value //格式如下
[["key1":value1],["key2":value2]]
Json::Value::const_iterator iter; //迭代器
for(iter = input.begin(); iter != input.end(); iter++)
Json::Value::Members member=(*iter).getMemberNames();
*(member.begin()); // 输出 key1,key2
(*iter)[*(member.begin())]; //输出 value1,value2
Value类是库中的核心类,用于存储各样格式的数据,可以包括int,double,short,char *,string,bool,object,array等几乎所有格式的数据。该库的编码和解码的核心功能都是用Value类实现的。就用以上的 Reader的parse方法来说,需要传入一个Value类别的引用值,就是用来存储Json数据的根值,并且可以用这个根值来存取其他的所有值。
(3) 对象访问
直接用 value["key"]即可
(4) 输出json格式串
调用 Json::FastWriter的writer
writer是该库的一个虚类,没有真正的实现encode的功能。需要重载里头的方法来实现真正的encode功能。FastWriter是该库中真正实现encode功能的类,用来实现将Value编码称为Json串。Json::StyledWriter 是格式化后的json。
不支持utf-8格式的输出,需要自己调用writer之后,用iconv转化成utf-8字符串
2、示例代码
1)示例代码1
复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <iostream>
#include "json/json.h"
using namespace std;
typedef struct piece 
{
    string letter;
    string wild;    
}piece;
string encode_msg(string token,int game_id,vector<piece> piece_array)
{
    //Json::Value root;
    Json::Value var;
    //apply “token” and “game_id” value to json struct
    var["token"] = token;
    var["game_id"] = game_id;
Json::Value pieces;//store all pieces
    for (int i=0;i < piece_array.size();i++)
    {
        Json::Value piece_ex;//here it store just one piece
        //next 4 lines to apply piece value to json struct
        piece_ex["letter"] = piece_array[i].letter;
        piece_ex["wild"] = piece_array[i].wild;
        //ok,yes we just have apply One piece ,then push back to the array
        pieces.append(piece_ex);
    }
    var["piece_array"] = pieces;//yes,store pieces in var [Value]
    //root.append(var);
Json::FastWriter writer;
    return writer.write(var);//generate json string:),here all is done
}
int main()
{
    piece one, two;
    one.letter = "1";
    one.wild = "ont";
    two.letter = "2";
    two.wild = "two";
    vector<piece> myp;
    myp.push_back(one);
    myp.push_back(two);
    string ret = encode_msg("mytoken", 123, myp);
    cout << ret << endl;
    return 1;
}
复制代码
{"game_id":123,"piece_array":[{"letter":"1","wild":"ont"},{"letter":"2","wild":"two"}],"token":"mytoken"}
结果显示
可以看到,直接用wirter输出的json为非格式化的数据,而通过root.toStyledString()后,代码就是格式化的。
2)示例3,来源于官网
复制代码
// Configuration options
{
    // Default encoding for text
    "encoding" : "UTF-8",
// Plug-ins loaded at start-up
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],
// Tab indent size
    "indent" : { "length" : 3, "use_space": true }
}
复制代码
复制代码
Json::Value root;   // will contains the root value after parsing.
Json::Reader reader;
bool parsingSuccessful = reader.parse( config_doc, root );
if ( !parsingSuccessful )
{
    // report to the user the failure and their locations in the document.
    std::cout  << "Failed to parse configuration\n"
               << reader.getFormattedErrorMessages();
    return;
}
// Get the value of the member of root named 'encoding', return 'UTF-8' if there is no
// such member.
std::string encoding = root.get("encoding", "UTF-8" ).asString();
// Get the value of the member of root named 'encoding', return a 'null' value if
// there is no such member.
const Json::Value plugins = root["plug-ins"];
for ( int index = 0; index < plugins.size(); ++index )  // Iterates over the sequence elements.
   loadPlugIn( plugins[index].asString() );
setIndentLength( root["indent"].get("length", 3).asInt() );
setIndentUseSpace( root["indent"].get("use_space", true).asBool() );
// ...
// At application shutdown to make the new configuration document:
// Since Json::Value has implicit constructor for all value types, it is not
// necessary to explicitly construct the Json::Value object:
root["encoding"] = getCurrentEncoding();
root["indent"]["length"] = getCurrentIndentLength();
root["indent"]["use_space"] = getCurrentIndentUseSpace();
Json::StyledWriter writer;
// Make a new JSON document for the configuration. Preserve original comments.
std::string outputConfig = writer.write( root );
// You can also use streams.  This will put the contents of any JSON
// stream at a particular sub-value, if you'd like.
std::cin >> root["subtree"];
// And you can write to a stream, using the StyledWriter automatically.
std::cout << root;
转自:https://www.cnblogs.com/mydomain/archive/2011/11/08/2241654.html
JSON函数表2的更多相关文章
- JSON函数表1
		jsoncpp 主要包含三个class:Value.Reader.Writer.注意Json::Value 只能处理 ANSI 类型的字符串,如果 C++ 程序是用 Unicode 编码的,最好加一个 ... 
- JSON函数表
		jsoncpp 主要包含三个class:Value.Reader.Writer.注意Json::Value 只能处理 ANSI 类型的字符串,如果 C++ 程序是用 Unicode 编码的,最好加一个 ... 
- C++ 虚函数表解析
		转载:陈皓 http://blog.csdn.net/haoel 前言 C++中 的虚函数的作用主要是实现了多态的机制.关于多态,简而言之就是用父类型别的指针指向其子类的实例,然后通过父类的指针调用实 ... 
- C++ 多态、虚函数机制以及虚函数表
		1.非virtual函数,调用规则取决于对象的显式类型.例如 A* a = new B(); a->display(); 调用的就是A类中定义的display().和对象本体是B无关系. 2. ... 
- C++迟后联编和虚函数表
		先看一个题目: class Base { public: virtual void Show(int x) { cout << "In Base class, int x = & ... 
- C++ 知道虚函数表的存在
		今天翻看陈皓大大的博客,直接找关于C++的东东,看到了虚函数表的内容,找一些能看得懂的地方记下笔记. 0 引子 类中存在虚函数,就会存在虚函数表,在vs2015的实现中,它存在于类的头部. 假设有如下 ... 
- C++虚函数和虚函数表
		前导 在上面的博文中描述了基类中存在虚函数时,基类和派生类中虚函数表的结构. 在派生类也定义了虚函数时,函数表又是怎样的结构呢? 先看下面的示例代码: #include <iostream> ... 
- C++ Daily 《5》----虚函数表的共享问题
		问题: 包含一个以上虚函数的 class B, 它所定义的 对象是否共用一个虚函数表? 分析: 由于含有虚函数,因此对象内存包含了一个指向虚函数表的指针,但是这个指针指向的是同一个虚函数表吗? 实验如 ... 
- C++虚函数表
		大家知道虚函数是通过一张虚函数表来实现的.在这个表中,主要是一个类的虚函数的地址表,这张表解决了继承.覆盖的问题,其内容真是反应实际的函数.这样,在有虚函数的类的实例中,这个表分配在了这个实例的内存中 ... 
随机推荐
- moveUp()
			这个函数内容有点多,想讲一下大概思路: 向上移有两种情况1.前面为空白 这种情况有两个步骤 (1)将人当前的位置设置为空白(0), (2)再讲人前面的位置设置为人(2)2.前面为箱子 当前面为箱子时有 ... 
- Nginx-HTTP之ngx_http_top_header_filter
			1. ngx_http_top_header_filter 该链表主要是用于构造响应消息的消息报头. ngx_http_top_header_filter 单链表有如下模块插入了操作: ngx_htt ... 
- Fast R-CNN论文阅读摘要
			论文链接: https://arxiv.org/pdf/1504.08083.pdf 代码下载: https://github.com/rbgirshick/fast-rcnn Abstract Co ... 
- 【论文学习】A Fuzzy-Rule-Based Approach for Single Frame Super Resolution
			加尔各答印度统计研究所,作者: Pulak Purkait (pulak_r@isical.ac.in) 2013 年 代码:CodeForge.cn http://www.codeforge.cn/ ... 
- LC 980. Unique Paths III
			On a 2-dimensional grid, there are 4 types of squares: 1 represents the starting square. There is e ... 
- 开机自动挂载ISO文件
			开机自动挂载ISO文件 Table of Contents 1. 概述 1.1. 通过fstab 1.2. 通过rc.local 1 概述 开机自动挂载ISO 文件有两种途径 .一种是通过配置fsta ... 
- UmUtils得到友盟的渠道号
			import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm ... 
- vlc 详细使用方法:libvlc_media_add_option 函数中的参数设置
			vlc 详细使用方法:libvlc_media_add_option 函数中的参数设置 [转载自]tinyle的专栏 [原文链接地址]http://blog.csdn.net/myaccella/ar ... 
- Spring Cloud(0):目录
			Spring Cloud(1):概览 Spring Cloud(2):服务发现(Eureka) Spring Cloud(3):配置服务(Config) Spring Cloud(4):断路器(Hys ... 
- Python 网络通信协议(互联网协议)
			一. 操作系统基础 操作系统(Operatin System,简称OS)是管理和控制计算机硬件与软件资源的计算机程序,是直接运行在"裸机"上的最基本的系统软件,任何其他软件都必须在 ... 
