更多API参考jsoncpp头文件
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
for (Json::ValueIterator iter=groups_config.begin(); iter!=groups_config.end();iter++) {
Json::Value client_dict = (*iter)["clients"];
string topic_recresult = (*iter)["topics"]["recresult"].asString();
string topic_recreq = (*iter)["topics"]["recreq"].asString();
string topic_input = (*iter)["topics"]["input"].asString();
for (Json::ValueIterator client_iter=client_dict.begin(); client_iter != client_dict.end(); ++client_iter) {
string cid = client_iter.key().asString();
// FIXME: create a new customer configuration
CustomerPtr c(new Customer);
c->LoadFromJson(cid, (*client_iter), topic_recresult, topic_recreq, topic_input);
customers[cid] = c;
}
}
2 详细API
</pre><pre code_snippet_id="342950" snippet_file_name="blog_20140513_1_8471295" name="code" class="cpp">class JSONAPI_API JsonValue
{
typedef std::map<std::string, JsonValue*> InnerMap;
typedef std::vector<JsonValue*> InnerVector;
public:
JsonValue();
virtual ~JsonValue();
public:
void clear();
//import/export
void parse(const char* jsonString);
JsonString toString();
JsonString toString_styled();
void toFile(const char* filename);
void toFile_styled(const char* filename);
//set
void operator=(JsonValue& jval);
void operator=(char vInteger);
void operator=(unsigned char vInteger);
void operator=(short vInteger);
void operator=(unsigned short vInteger);
void operator=(long vInteger);
void operator=(unsigned long vInteger);
void operator=(int vInteger);
void operator=(unsigned int vInteger);
void operator=(__int64 vInteger);
void operator=(unsigned __int64 vInteger);
void operator=(float vReal);
void operator=(double vReal);
void operator=(bool vBoolean);
void operator=(const char* vString);
int append(JsonValue& jval);
int append(char vInteger);
int append(unsigned char vInteger);
int append(short vInteger);
int append(unsigned short vInteger);
int append(long vInteger);
int append(unsigned long vInteger);
int append(int vInteger);
int append(unsigned int vInteger);
int append(__int64 vInteger);
int append(unsigned __int64 vInteger);
int append(float vReal);
int append(double vReal);
int append(bool vBoolean);
int append(const char* vString);
//get
JsonValue& operator [](const char* name);
JsonValue& operator [](unsigned int arrIdx0);
//get final value
char getChar();
unsigned char getUChar();
short getShort();
unsigned short getUShort();
long getLong();
unsigned long getULong();
int getInt();
unsigned int getUInt();
__int64 getInt64();
unsigned __int64 getUInt64();
bool getBoolean();
float getFloat();
double getDouble();
const char* getString();
//check
bool isNull();
bool isChar();
bool isUChar();
bool isShort();
bool isUShort();
bool isLong();
bool isULong();
bool isInt();
bool isUInt();
bool isInt64();
bool isUInt64();
bool isBoolean();
bool isFloat();
bool isDouble();
bool isString();
bool isObject();
bool isArray();
protected:
ValueType m_valueType;
union
{
__int64 m_integer;
double m_real;
bool m_boolean;
char* m_string;
InnerMap* m_kv;
InnerVector* m_array;
}m_v;
protected:
void setAsObject();
void setAsArray();
friend JValHelper;
};
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 : json cpp test
*/
#include <fstream>
#include <string>
#include "jsoncpp/json.h"
int _tmain(int argc, _TCHAR* argv[])
{
std::ifstream ifs;
ifs.open("test.json");
Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{ return -1; }
Json::Value add_value = root["address"];
for (int i = 0; i < add_value.size(); ++i)
{
Json::Value temp_value = add_value[i];
std::string strName = temp_value["name"].asString();
std::string strMail = temp_value["email"].asString();
std::cout << "name: " << strName << " email: " << strMail << std::endl;
// use value array[index]
//Json::Value temp_value = add_value[i];
//std::string strName = add_value[i]["name"].asString();
//std::string strMail = add_value[i]["email"].asString();
//std::cout << "name: " << strName << " email: " << strMail << std::endl;
}
system("Pause");
return 0;
}
结果:
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"}
/**
* file : jsoncpp_test.cpp
* author : eliteYang
* email : elite_yang@163.com
* blog : http://www.cppfasn.org
* desc : json cpp test
*/
#include <fstream>
#include <string>
#include "jsoncpp/json.h"
int _tmain(int argc, _TCHAR* argv[])
{
std::ifstream ifs;
ifs.open("test.json");
Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{ return -1; }
Json::Value& add_value = root["address"];
Json::Value append_value;
append_value["name"] = "append";
append_value["email"] = "append@163.com";
add_value.append(append_value);
for (int i = 0; i < add_value.size(); ++i)
{
Json::Value temp_value = add_value[i];
std::string strName = temp_value["name"].asString();
std::string strMail = temp_value["email"].asString();
std::cout << "name: " << strName << " email: " << strMail << std::endl;
}
Json::FastWriter writer;
std::string json_append_file = writer.write(root);
std::ofstream ofs;
ofs.open("test_append.json");
ofs << json_append_file;
system("Pause");
return 0;
}
结果:
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
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$ 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文件
./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 : json number : 666 value : 1 no such num : 0 no such str : arrnum[0] = null arrnum[1] = 1 arrnum[2] = 2 arrnum[3] = 3 arrnum[4] = 4 arrnum[5] = 5 arrnum[6] = 6 array size = 1 { "aaaaaa" : "bbbbbb", "number" : 999, "string" : "this is a string" } string : this is a string --------------------------------
作者:风波
mail : fengbohello@qq.com
jsoncpp使用优化:http://www.searchtb.com/2012/11/jsoncpp-optimization.html