1 jsoncpp的api简要说明
1,解析(json字符串转为对象)
std::stringstrDataJson;
Json::ReaderJReader;
Json::ValueJObject;
if(!JReader.parse(strDataJson,JObject))
{
cerr<<"parsejsonerror."<<endl;
returnbSuccess;
}
2,读取
std::stringstrMsg=JRec["msg"].asString();
intnRetCode=JRec["ret"]..asInt();
Json::ValueJList=JRec["data"]["list"];
intnSize=JList.size();
获取错误信息:JReader.getFormatedErrorMessages()
3,增加或修改
JRoot["stringdata"]=Json::Value("msg");
JRoot["intdata"]=Json::Value(10);
4,删除
JValue.removeMember("toberemove");
5,对象转为字符串
//
Json::FastWriterfast_writer;
strJRecList=fast_writer.write(JRoot);
//格式化之后的json,有回车换行符
std::stringstrOut=JRoot.toStyledString();
转自;http://my.oschina.net/chenleijava/blog/144312
6各种json子类型的使用
(1)json Object
- for(Json::ValueIteratoriter=groups_config.begin();iter!=groups_config.end();iter++){
- Json::Valueclient_dict=(*iter)["clients"];
- stringtopic_recresult=(*iter)["topics"]["recresult"].asString();
- stringtopic_recreq=(*iter)["topics"]["recreq"].asString();
- stringtopic_input=(*iter)["topics"]["input"].asString();
- for(Json::ValueIteratorclient_iter=client_dict.begin();client_iter!=client_dict.end();++client_iter){
- stringcid=client_iter.key().asString();
-
- CustomerPtrc(newCustomer);
- c->LoadFromJson(cid,(*client_iter),topic_recresult,topic_recreq,topic_input);
- customers[cid]=c;
- }
- }
2 详细API
</pre><precode_snippet_id="342950"snippet_file_name="blog_20140513_1_8471295"name="code"class="cpp">classJSONAPI_APIJsonValue
- {
- typedefstd::map<std::string,JsonValue*>InnerMap;
- typedefstd::vector<JsonValue*>InnerVector;
-
- public:
- JsonValue();
- virtual~JsonValue();
- voidclear();
-
-
- voidparse(constchar*jsonString);
- JsonStringtoString();
- JsonStringtoString_styled();
- voidtoFile(char*filename);
- voidtoFile_styled(char*filename);
- //set
- voidoperator=(JsonValue&jval);
- voidoperator=(charvInteger);
- voidoperator=(unsignedcharvInteger);
- shortvInteger);
- shortvInteger);
- longvInteger);
- longvInteger);
- intvInteger);
- intvInteger);
- __int64vInteger);
- __int64vInteger);
- floatvReal);
- doublevReal);
- boolvBoolean);
- voidoperator=(char*vString);
- intappend(JsonValue&jval);
- intappend(intappend(unsignedintappend(//get
- JsonValue&operator[](char*name);
- JsonValue&operator[](unsignedintarrIdx0);
- //getfinalvalue
- chargetChar();
- unsignedchargetUChar();
- shortgetShort();
- shortgetUShort();
- longgetLong();
- longgetULong();
- intgetInt();
- intgetUInt();
- __int64getInt64();
- __int64getUInt64();
- boolgetBoolean();
- floatgetFloat();
- doublegetDouble();
- char*getString();
- //check
- boolisNull();
- boolisChar();
- boolisUChar();
- boolisShort();
- boolisUShort();
- boolisLong();
- boolisULong();
- boolisInt();
- boolisUInt();
- boolisInt64();
- boolisUInt64();
- boolisBoolean();
- boolisFloat();
- boolisDouble();
- boolisString();
- boolisObject();
- boolisArray();
- protected:
- ValueTypem_valueType;
- union
- __int64m_integer;
- doublem_real;
- boolm_boolean;
- char*m_string;
- InnerMap*m_kv;
- InnerVector*m_array;
- }m_v;
- voidsetAsObject();
- voidsetAsArray();
- friendJValHelper;
- };
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工程中在此就不赘述了。先看第一个读文件的例
//JSON文件
- {"address":[
- {"name":"eliteYang","email":"elite_yang@163.com"},
- {"name":"AAA","email":"aaa@163.com"},
- {"name":"BBB","email":"bbb@163.com"}
- ]}
/**
- *file:jsoncpp_test.cpp
- *author:eliteYang
- *email:elite_yang@163.com
- *blog:http://www.cppfasn.org
- *desc:jsoncpptest
- */
- #include<fstream>
- #include<string>
- #include"jsoncpp/json.h"
- int_tmain(intargc,_TCHAR*argv[])
- std::ifstreamifs;
- ifs.open("test.json");
- Json::Readerreader;
- Json::Valueroot;
- if(!reader.parse(ifs,root,false))
- {return-1;}
- Json::Valueadd_value=root["address"];
- for(inti=0;i<add_value.size();++i)
- {
- Json::Valuetemp_value=add_value[i];
- std::stringstrName=temp_value["name"].asString();
- std::stringstrMail=temp_value["email"].asString();
- std::cout<<"name:"<<strName<<"email:"<<strMail<<std::endl;
- //usevaluearray[index]
- //Json::Valuetemp_value=add_value[i];
- //std::stringstrName=add_value[i]["name"].asString();
- //std::stringstrMail=add_value[i]["email"].asString();
- //std::cout<<"name:"<<strName<<"email:"<<strMail<<std::endl;
- system("Pause");
- return0;
- }
结果:
name: eliteYang email: elite_yang@163.com
name: AAA email: aaa@163.com
name: BBB email: bbb@163.com
请按任意键继续. . .
跟我们文件中的数据完全一致。
4.使用JSON写入一块数据
我们继续使用上述文件,在中间加上一块数据。我们插入一个新的{"name": "append","email": "append@163.com"}
Json::Value&add_value=root["address"];
- Json::Valueappend_value;
- append_value["name"]="append";
- append_value["email"]="append@163.com";
- add_value.append(append_value);
- inti=0;i<add_value.size();++i)
- Json::Valuetemp_value=add_value[i];
- std::stringstrName=temp_value["name"].asString();
- std::stringstrMail=temp_value["email"].asString();
- std::cout<<"name:"<<strName<<"email:"<<strMail<<std::endl;
- }
- Json::FastWriterwriter;
- std::stringjson_append_file=writer.write(root);
- std::ofstreamofs;
- ofs.open("test_append.json");
- ofs<<json_append_file;
- name: eliteYang email: elite_yang@163.com
name: AAA email: aaa@163.com
name: BBB email: bbb@163.com
name: append email: append@163.com
请按任意键继续. . .
//test_append.json
- {"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
3)修改jsoncpp/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<< 18 cout<< json read :" << endl;
19 ReadJson(strMsg);
20 cout<< 21
22 return 0;
23 }
24
25 string & strValue)
26 {
27 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 : haha 40 cout << no such str : 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 0; i < arrayObj.size(); i++)
52 {
53 cout << arrayObj[i];
54 }
55 从对象数组中找到想要的对象
56 57 {
58 if (arrayObj[i].isMember(string"))
59 {
60 out = arrayObj[i][ 61 std::cout << string : " << out << std::endl;
62 }
63 }
64 }
65
66 67 }
68
69 std::string writeJson()
70 {
71 72
73 Json::Value root;
74 Json::Value arrayObj;
75 Json::Value item;
76 Json::Value iNum;
77
78 item["] = this is a string";
79 item[999;
80 item[aaaaaabbbbbb 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["] = arrayObj;
93 增加字符串
94 root[json 95 增加数字
96 root[666;
97 增加布尔变量
98 root["] = true;
99 增加数字数组
100 root["] = iNum;
101
102 root.toStyledString();
103 out = root.toStyledString();
104
105 return out;
106 }
4)在目录jsoncpp/ 下执行make命令
jsoncpp$ make
mkdir -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.o
g++ -c -Wall -Werror -g -I include src/json/json_value.cpp -o objs/src/json/json_value.o
g++ -c -Wall -Werror -g -I include src/json/json_writer.cpp -o objs/src/json/json_writer.o
g++ -c -Wall -Werror -g -I include src/main.cpp -o objs/src/main.o
g++ 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文件
6)运行结果如下
fengbo: jsoncpp$ ./main
--------------------------------
json write :
{
" : [
{
" : ",999,0); line-height:1.5!important">"
}
],0); line-height:1.5!important">" : [ null,1,128); line-height:1.5!important">2 ,128); line-height:1.5!important">3,128); line-height:1.5!important">4,128); line-height:1.5!important">5,128); line-height:1.5!important">6 ],128); line-height:1.5!important">666,0); line-height:1.5!important">" : true
}
--------------------------------
json read :
name : json
number : 666
value : 1
no such num : 0
no such str :
arrnum[0] = null
arrnum[1
arrnum[2
arrnum[3
arrnum[4
arrnum[5
arrnum[6
array size = 1
{
"
}
string : this is a string
--------------------------------
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|