jso cpp解析读写数据
作者:互联网
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 }
写数据:
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 }
读数据:
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 }
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 }
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,读写,jso,number,json,iNum,cpp,root,arrnum 来源: https://www.cnblogs.com/wangjian8888/p/10797345.html