Json-5.0
另可参考https://www.cnblogs.com/yelongsan/p/4134384.html
1 #include <string> 2 #include <json/json.h> 3 #include <stdio.h> 4 #include <fstream> 5 using namespace std; 6 7 void readStrJson(); //从字符串中读取JSON 8 void readStrProJson(); //从字符串中读取JSON(内容复杂些) 9 10 int main(int argc, char *argv[]) 11 { 12 readStrJson(); 13 14 cout << "\n\n"; 15 readStrProJson(); 16 system("pause"); 17 return 0; 18 } 19 20 //从字符串中读取JSON 21 void readStrJson() 22 { 23 //字符串 24 const char* str = 25 "{\"praenomen\":\"Gaius\",\"nomen\":\"Julius\",\"cognomen\":\"Caezar\"," 26 "\"born\":-100,\"died\":-44}"; 27 28 /* 29 //json内容如下: 30 { 31 "praenomen":"Gaius", 32 "nomen":"Julius", 33 "cognomen":"Caezar", 34 "born":-100, 35 "died":-44 36 } 37 */ 38 39 Json::Reader reader; 40 Json::Value root; 41 42 //从字符串中读取数据 43 if (reader.parse(str, root)) 44 { 45 string praenomen = root["praenomen"].asString(); 46 string nomen = root["nomen"].asString(); 47 string cognomen = root["cognomen"].asString(); 48 int born = root["born"].asInt(); 49 int died = root["died"].asInt(); 50 51 cout << praenomen + " " + nomen + " " + cognomen 52 << " was born in year " << born 53 << ", died in year " << died << endl; 54 } 55 56 } 57 58 //从字符串中读取JSON(内容复杂些) 59 void readStrProJson() 60 { 61 string strValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}";//1,3 62 /* 63 //json内容如下: 64 { 65 "name": "json″, 66 "array": [ //【一个数组】 67 { 68 "cpp": "jsoncpp" 69 }, 70 { 71 "java": "jsoninjava" 72 }, 73 { 74 "php": "support" 75 } 76 ] 77 } 78 */ 79 80 81 Json::Reader reader; 82 Json::Value value; 83 84 if (reader.parse(strValue, value)) 85 { 86 string out = value["name"].asString(); 87 cout << out << endl; 88 const Json::Value arrayObj = value["array"]; 89 for (unsigned int i = 0; i < arrayObj.size(); i++) 90 { 91 if (!arrayObj[i].isMember("cpp")) 92 continue; 93 out = arrayObj[i]["cpp"].asString(); 94 cout << out; 95 if (i != (arrayObj.size() - 1)) 96 cout << endl; 97 } 98 } 99 } 100