以前项目中咱们客户端程序一直是使用XML与服务器通讯,最近新增一些接口转向使用更简单的Json。咱们都知道因为Json语法是 JavaScript 对象表示语法的子集。因此在Java,JavaScript等语言中使用起来是十分愉快的。在C++中咱们使用跨平台的开源库JsonCpp也能愉快的玩耍Json。
GitHub:https://github.com/open-sourc...ios
方法一:使用Jsoncpp包中的.cpp和.h文件git
方法二:使用Jsoncpp生成的lib文件 github
JsonCpp 主要包含三种类型的 class:Value、Reader、Writer。JsonCpp 中全部对象、类名都在 namespace Json 中,包含 json.h 便可。
Json::Value 只能处理 ANSI 类型的字符串,若是 C++ 程序是用 Unicode 编码的,最好加一个 Adapt 类来适配。json
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");