jsoncpp的api简要说明

来源:互联网 发布:汉字的意义和作用 知乎 编辑:程序博客网 时间:2024/05/01 12:50

1  jsoncpp的api简要说明

1,解析(json字符串转为对象)

std::string strDataJson;

Json::Reader JReader; 

Json::Value JObject;

if (!JReader.parse(strDataJson, JObject))

{

cerr << "parse json error." << endl;

return bSuccess;

}


2,读取

std::string strMsg = JRec["msg"].asString();

int nRetCode = JRec["ret"]..asInt();

Json::Value JList = JRec["data"]["list"];

int nSize = JList.size();


获取错误信息: JReader.getFormatedErrorMessages()


3,增加或修改

JRoot["stringdata"] = Json::Value("msg");

JRoot["intdata"] = Json::Value(10);


4,删除

JValue.removeMember("toberemove");


5,对象转为字符串

//输出无格式json字符串

Json::FastWriter fast_writer;

strJRecList = fast_writer.write(JRoot);


//格式化之后的json,有回车换行符

std::string strOut = JRoot.toStyledString();

转自;http://my.oschina.net/chenleijava/blog/144312


6各种json子类型的使用

(1)json Object 

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. for (Json::ValueIterator iter=groups_config.begin(); iter!=groups_config.end();iter++) {  
  2.      Json::Value client_dict = (*iter)["clients"];  
  3.      string topic_recresult = (*iter)["topics"]["recresult"].asString();  
  4.      string topic_recreq = (*iter)["topics"]["recreq"].asString();  
  5.      string topic_input = (*iter)["topics"]["input"].asString();  
  6.      for (Json::ValueIterator client_iter=client_dict.begin(); client_iter != client_dict.end(); ++client_iter) {  
  7.        string cid = client_iter.key().asString();  
  8.        // FIXME: create a new customer configuration  
  9.        CustomerPtr c(new Customer);  
  10.        c->LoadFromJson(cid, (*client_iter), topic_recresult, topic_recreq, topic_input);  
  11.        customers[cid] = c;  
  12.      }  
  13.    }  



2 详细API

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. </pre><pre code_snippet_id="342950" snippet_file_name="blog_20140513_1_8471295" name="code" class="cpp">class JSONAPI_API JsonValue  
  2.     {  
  3.         typedef std::map<std::string, JsonValue*> InnerMap;  
  4.         typedef std::vector<JsonValue*>               InnerVector;  
  5.   
  6.     public:  
  7.         JsonValue();  
  8.         virtual ~JsonValue();  
  9.   
  10.     public:  
  11.         void clear();  
  12.   
  13.         //import/export  
  14.         void parse(const char* jsonString);  
  15.         JsonString toString();  
  16.         JsonString toString_styled();  
  17.         void toFile(const char* filename);  
  18.         void toFile_styled(const char* filename);  
  19.   
  20.         //set  
  21.         void operator=(JsonValue& jval);  
  22.   
  23.         void operator=(char vInteger);  
  24.         void operator=(unsigned char vInteger);  
  25.         void operator=(short vInteger);  
  26.         void operator=(unsigned short vInteger);  
  27.         void operator=(long vInteger);  
  28.         void operator=(unsigned long vInteger);  
  29.         void operator=(int vInteger);  
  30.         void operator=(unsigned int vInteger);  
  31.         void operator=(__int64 vInteger);  
  32.         void operator=(unsigned __int64 vInteger);  
  33.         void operator=(float vReal);  
  34.         void operator=(double vReal);  
  35.         void operator=(bool vBoolean);  
  36.         void operator=(const char* vString);  
  37.   
  38.         int append(JsonValue& jval);  
  39.         int append(char vInteger);  
  40.         int append(unsigned char vInteger);  
  41.         int append(short vInteger);  
  42.         int append(unsigned short vInteger);  
  43.         int append(long vInteger);  
  44.         int append(unsigned long vInteger);  
  45.         int append(int vInteger);  
  46.         int append(unsigned int vInteger);  
  47.         int append(__int64 vInteger);  
  48.         int append(unsigned __int64 vInteger);  
  49.         int append(float vReal);  
  50.         int append(double vReal);  
  51.         int append(bool vBoolean);  
  52.         int append(const char* vString);  
  53.   
  54.         //get  
  55.         JsonValue& operator [](const char* name);  
  56.         JsonValue& operator [](unsigned int arrIdx0);  
  57.   
  58.         //get final value  
  59.         char            getChar();  
  60.         unsigned char   getUChar();  
  61.         short           getShort();  
  62.         unsigned short  getUShort();  
  63.         long            getLong();  
  64.         unsigned long   getULong();  
  65.         int             getInt();  
  66.         unsigned int    getUInt();  
  67.         __int64         getInt64();  
  68.         unsigned __int64 getUInt64();  
  69.         bool            getBoolean();  
  70.         float           getFloat();  
  71.         double          getDouble();  
  72.         const char*     getString();  
  73.   
  74.         //check  
  75.         bool isNull();  
  76.         bool isChar();  
  77.         bool isUChar();  
  78.         bool isShort();  
  79.         bool isUShort();  
  80.         bool isLong();  
  81.         bool isULong();  
  82.         bool isInt();  
  83.         bool isUInt();  
  84.         bool isInt64();  
  85.         bool isUInt64();  
  86.         bool isBoolean();  
  87.         bool isFloat();  
  88.         bool isDouble();  
  89.         bool isString();  
  90.         bool isObject();  
  91.         bool isArray();  
  92.   
  93.     protected:  
  94.         ValueType m_valueType;  
  95.         union  
  96.         {  
  97.             __int64 m_integer;  
  98.             double m_real;  
  99.             bool m_boolean;  
  100.             char* m_string;  
  101.             InnerMap* m_kv;  
  102.             InnerVector* m_array;  
  103.         }m_v;  
  104.   
  105.     protected:  
  106.         void setAsObject();  
  107.         void setAsArray();  
  108.   
  109.         friend JValHelper;  
  110.     };  



1.jsoncpp是什么?

jsoncpp是一个使用C++语言来解析json文件的开源库,其项目地址为:http://sourceforge.net/projects/jsoncpp/,属于免费项目,任何人都可以下载使用

2. 编译jsoncpp

jsoncpp文件中提供了vs71的工程文件以及makerelease.py文件,用来编译,里面分为jsontest、lib_json、test_lib_json三个工程,按照自己需要的编译。

注意:如果使用VS默认的编译选项MTd或者MT,在使用json_libmtd.lib的时候可能会出现LNK2038错误(我使用的VS2012 vc110环境)所以请修改MTD为MDd,MT为MD

3.使用jsoncpp读JSON文件

如何将lib库添加进VS工程中在此就不赘述了。先看第一个读文件的例

[js] view plaincopy
  1. // JSON文件  
  2. {"address":[  
  3.     {"name":"eliteYang""email":"elite_yang@163.com"},  
  4.     {"name":"AAA""email":"aaa@163.com"},  
  5.     {"name":"BBB""email":"bbb@163.com"}  
  6. ]}  

[cpp] view plaincopy
  1. /** 
  2.  * file     :   jsoncpp_test.cpp 
  3.  * author   :   eliteYang 
  4.  * email    :   elite_yang@163.com 
  5.  * blog     :   http://www.cppfasn.org 
  6.  * desc     :   json cpp test 
  7.  */  
  8.    
  9. #include <fstream>  
  10. #include <string>  
  11. #include "jsoncpp/json.h"  
  12.    
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.     std::ifstream ifs;  
  16.     ifs.open("test.json");  
  17.    
  18.     Json::Reader reader;  
  19.     Json::Value root;  
  20.     if (!reader.parse(ifs, root, false))  
  21.     { return -1; }  
  22.    
  23.     Json::Value add_value = root["address"];  
  24.     for (int i = 0; i < add_value.size(); ++i)  
  25.     {  
  26.         Json::Value temp_value = add_value[i];  
  27.         std::string strName = temp_value["name"].asString();  
  28.         std::string strMail = temp_value["email"].asString();  
  29.         std::cout << "name: " << strName << " email: " << strMail << std::endl;  
  30.    
  31.         // use value array[index]  
  32.         //Json::Value temp_value = add_value[i];  
  33.         //std::string strName = add_value[i]["name"].asString();  
  34.         //std::string strMail = add_value[i]["email"].asString();  
  35.         //std::cout << "name: " << strName << " email: " << strMail << std::endl;  
  36.     }  
  37.    
  38.     system("Pause");  
  39.    
  40.     return 0;  
  41. }  

结果:

name: eliteYang email: elite_yang@163.comname: AAA email: aaa@163.comname: BBB email: bbb@163.com请按任意键继续. . .

跟我们文件中的数据完全一致。

4.使用JSON写入一块数据

我们继续使用上述文件,在中间加上一块数据。我们插入一个新的{"name": "append", "email": "append@163.com"}

[cpp] view plaincopy
  1. /** 
  2.  * file     :   jsoncpp_test.cpp 
  3.  * author   :   eliteYang 
  4.  * email    :   elite_yang@163.com 
  5.  * blog     :   http://www.cppfasn.org 
  6.  * desc     :   json cpp test 
  7.  */  
  8.    
  9. #include <fstream>  
  10. #include <string>  
  11. #include "jsoncpp/json.h"  
  12.    
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.     std::ifstream ifs;  
  16.     ifs.open("test.json");  
  17.    
  18.     Json::Reader reader;  
  19.     Json::Value root;  
  20.     if (!reader.parse(ifs, root, false))  
  21.     { return -1; }  
  22.    
  23.     Json::Value& add_value = root["address"];  
  24.     Json::Value append_value;  
  25.     append_value["name"] = "append";  
  26.     append_value["email"] = "append@163.com";  
  27.     add_value.append(append_value);  
  28.    
  29.     for (int i = 0; i < add_value.size(); ++i)  
  30.     {  
  31.         Json::Value temp_value = add_value[i];  
  32.         std::string strName = temp_value["name"].asString();  
  33.         std::string strMail = temp_value["email"].asString();  
  34.         std::cout << "name: " << strName << " email: " << strMail << std::endl;  
  35.     }  
  36.    
  37.     Json::FastWriter writer;  
  38.     std::string json_append_file = writer.write(root);  
  39.    
  40.     std::ofstream ofs;  
  41.     ofs.open("test_append.json");  
  42.     ofs << json_append_file;  
  43.    
  44.     system("Pause");  
  45.    
  46.     return 0;  
  47. }  

结果:

name: eliteYang email: elite_yang@163.comname: AAA email: aaa@163.comname: BBB email: bbb@163.comname: append email: append@163.com请按任意键继续. . .
[js] view plaincopy
  1. // test_append.json  
  2. {"address":[{"email":"elite_yang@163.com","name":"eliteYang"},{"email":"aaa@163.com","name":"AAA"},{"email":"bbb@163.com","name":"BBB"},{"email":"append@163.com","name":"append"}]}  

转自:http://www.cppfans.org/1445.html



一个jsoncpp的例子

使用jsoncpp进行字符串、数字、布尔值和数组的封装与解析。

1)下载jsoncpp的代码库 百度网盘地址 :http://pan.baidu.com/s/1ntqQhIT

2)解压缩文件 jsoncpp.rar

unzip jsoncpp.rar

3)修改jsoncpp/src/main.cpp文件

vim src/main.cpp
复制代码
  1 #include <string>  2 #include <json/json.h>  3 #include "stdio.h"  4   5 int ReadJson(const std::string &);  6 std::string writeJson();  7   8 int main(int argc, char** argv)  9 { 10     using namespace std; 11  12     std::string strMsg; 13  14     cout<<"--------------------------------"<<endl; 15     strMsg = writeJson(); 16     cout<< "json write : " << endl << strMsg << endl; 17     cout<<"--------------------------------"<<endl; 18     cout<< "json read :" << endl; 19     ReadJson(strMsg); 20     cout<<"--------------------------------"<<endl; 21  22     return 0; 23 } 24  25 int ReadJson(const std::string & strValue)  26 { 27     using namespace std; 28  29     Json::Reader reader; 30     Json::Value value; 31  32     if (reader.parse(strValue, value)) 33     { 34         //解析json中的对象 35         string out = value["name"].asString(); 36         cout << "name : "   << out << endl; 37         cout << "number : " << value["number"].asInt() << endl; 38         cout << "value : "  << value["value"].asBool() << endl; 39         cout << "no such num : " << value["haha"].asInt() << endl; 40         cout << "no such str : " << value["hehe"].asString() << endl; 41  42         //解析数组对象 43         const Json::Value arrayNum = value["arrnum"]; 44         for (unsigned int i = 0; i < arrayNum.size(); i++) 45         { 46             cout << "arrnum[" << i << "] = " << arrayNum[i]; 47         } 48         //解析对象数组对象 49         Json::Value arrayObj = value["array"]; 50         cout << "array size = " << arrayObj.size() << endl; 51         for(unsigned int i = 0; i < arrayObj.size(); i++) 52         { 53             cout << arrayObj[i]; 54         } 55         //从对象数组中找到想要的对象 56         for(unsigned int i = 0; i < arrayObj.size(); i++) 57         { 58             if (arrayObj[i].isMember("string"))  59             { 60                 out = arrayObj[i]["string"].asString(); 61                 std::cout << "string : " << out << std::endl; 62             } 63         } 64     } 65  66     return 0; 67 } 68  69 std::string writeJson()  70 { 71     using namespace std; 72  73     Json::Value root; 74     Json::Value arrayObj; 75     Json::Value item; 76     Json::Value iNum; 77  78     item["string"]    = "this is a string"; 79     item["number"]    = 999; 80     item["aaaaaa"]    = "bbbbbb"; 81     arrayObj.append(item); 82  83     //直接对jsoncpp对象以数字索引作为下标进行赋值,则自动作为数组 84     iNum[1] = 1; 85     iNum[2] = 2; 86     iNum[3] = 3; 87     iNum[4] = 4; 88     iNum[5] = 5; 89     iNum[6] = 6; 90  91     //增加对象数组 92     root["array"]    = arrayObj; 93     //增加字符串 94     root["name"]    = "json"; 95     //增加数字 96     root["number"]    = 666; 97     //增加布尔变量 98     root["value"]    = true; 99     //增加数字数组100     root["arrnum"]    = iNum;101 102     root.toStyledString();103     string out = root.toStyledString();104 105     return out;106 }
复制代码

4)在目录jsoncpp/ 下执行make命令

复制代码
jsoncpp$ makemkdir -p objs/src/json;  mkdir -p objs/src;g++ -c -Wall -Werror -g -I include src/json/json_reader.cpp -o objs/src/json/json_reader.og++ -c -Wall -Werror -g -I include src/json/json_value.cpp -o objs/src/json/json_value.og++ -c -Wall -Werror -g -I include src/json/json_writer.cpp -o objs/src/json/json_writer.og++ -c -Wall -Werror -g -I include src/main.cpp -o objs/src/main.og++  objs/src/json/json_reader.o objs/src/json/json_value.o objs/src/json/json_writer.o objs/src/main.o -o main
复制代码

5)运行jsoncpp/下的main文件

./main

6)运行结果如下

复制代码
fengbo: jsoncpp$ ./main --------------------------------json write : {   "array" : [      {         "aaaaaa" : "bbbbbb",         "number" : 999,         "string" : "this is a string"      }   ],   "arrnum" : [ null, 1, 2, 3, 4, 5, 6 ],   "name" : "json",   "number" : 666,   "value" : true}--------------------------------json read :name : jsonnumber : 666value : 1no such num : 0no such str : arrnum[0] = nullarrnum[1] = 1arrnum[2] = 2arrnum[3] = 3arrnum[4] = 4arrnum[5] = 5arrnum[6] = 6array size = 1{    "aaaaaa" : "bbbbbb",    "number" : 999,    "string" : "this is a string"}string : this is a string--------------------------------
复制代码
0 0