C++ Json 的几个操作

1,读含有数组的json

const char* str = "{\"HELK\": [\"id\",\"name\",\"yantao\",\"gender\",\"Male\"],\"code\": 100,\"msg\": \"\",\"files\": \"\"}";  
Json::Reader reader;  
Json::Value root;  
if (reader.parse(str, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素   
{
    bool IsArray=root["HELK"].isArray();

    for(int i=0;i"HELK"].size();++i)
    {
        std::string  value=root["HELK"][i].toStyledString();
        printf("%s\n",value.c_str());
    }
}
   
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

JPG:
C++ Json 的几个操作_第1张图片


2.读obj里面的obj

const char* str = "{\"uploadid\": {\"id\":\"123454\",\"name\":\"yantao\",\"gender\":\"Male\"},\"code\": 100,\"msg\": \"\",\"files\": \"\"}";  
Json::Reader reader;  
Json::Value root;  
reader.parse(str, root);  // reader将Json字符串解析到root,root将包含Json里所有子元素   
Json::Value obj=root["uploadid"];
string str2 = obj["id"].asString();
printf("%s\n",str2.c_str());
   
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

JPG:
C++ Json 的几个操作_第2张图片


3.生成一个json

Json::Value root; 
root["id"]=1244235;
root["describe"]="how SB you are";
Json::StyledWriter sw;
std::string res_str = sw.write(root);
std::cout << res_str << std::endl;
   
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

C++ Json 的几个操作_第3张图片


4.生成一个json里面有数组

Json::Value root; 
root["id"]=1244235;
root["describe"]="how SB you are";
root["Arry"].append("123");
root["Arry"].append("213");
root["Arry"].append("321");
Json::StyledWriter sw;
std::string res_str = sw.write(root);
std::cout << res_str << std::endl;
   
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

C++ Json 的几个操作_第4张图片



转载至: https://blog.csdn.net/what951006/article/details/78864615

你可能感兴趣的:(C++)