之前项目中我们客户端程序一直是使用XML与服务器通信,最近新增一些接口转向使用更简单的Json。我们都知道由于Json语法是 JavaScript 对象表示语法的子集。所以在Java,JavaScript等语言中使用起来是十分愉快的。在C++中我们使用跨平台的开源库JsonCpp也能愉快的玩耍Json。
GitHub:https://github.com/open-source-parsers/jsoncpp
方法一:使用Jsoncpp包中的.cpp和.h文件
方法二:使用Jsoncpp生成的lib文件
JsonCpp 主要包含三种类型的 class:Value、Reader、Writer。JsonCpp 中所有对象、类名都在 namespace Json 中,包含 json.h 即可。
Json::Value 只能处理 ANSI 类型的字符串,如果 C++ 程序是用 Unicode 编码的,最好加一个 Adapt 类来适配。
std::string strValue = “{\”key\”:\”value1\”,\”array\”:[{\"arraykey\":1},{\"arraykey\":2}]}”; Json::Reader reader; Json::Value root; // reader将Json字符串解析到root,root将包含Json里所有子元素if (reader.parse(strValue, root)) { if (!root["key"].isNull()) { std::string strValue= root["key"].asString(); std::cout << strValue<< std::endl; } Json::Value arrayObj = root["array"]; for (int i=0; i<arrayObj.size(); i++) { int iarrayValue = arrayObj[i]["arraykey"].asInt(); std::cout << iarrayValue << std::endl; } }
Json::Value root; Json::Value arrayObj;Json::Value item; root["key"] = “value1″; for (int i=0; i<10; i++){ item["arraykey"] = i; arrayObj.append(item); //添加新的数组成员} root["array"] = arrayObj; std::string out = root.toStyledString(); //将Json对象序列化为字符串std::cout << out << std::endl;
void WriteJsonData(const char* filename){ Json::Reader reader; Json::Value root; ifstream is; is.open(filename, std::ios::binary); if (reader.parse(is, root, FALSE)) { Json::Value item; root["key"] = “value1″; //添加数组成员 item["arraykey"] = 2; root["array"].append(item) Json::FastWriter writer; string strWrite = writer.write(root); ofstream ofs; ofs.open(filename); ofs << strWrite; ofs.close(); } is.close(); }
root["array"].resize(0);
root.removeMember("key");
联系客服