C++ Json 变量的初始化

1、从字符串 解析

[cpp]  view plain  copy
  1. int ParseJsonFromString()  
  2. {  
  3.   const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";  
  4.   
  5.   Json::Reader reader;  
  6.   Json::Value root;  
  7.   if (reader.parse(str, root))  // reader将Json字符串解析到root,root将包含Json里所有子元素  
  8.   {  
  9.     std::string upload_id = root["uploadid"].asString();  // 访问节点,upload_id = "UP000000"  
  10.     int code = root["code"].asInt();    // 访问节点,code = 100  
  11.   }  
  12.   return 0;  
  13. }  

2、从文件中解析

数据格式:

{
    "uploadid": "UP000000",
    "code": "0",
    "msg": "",
    "files":
    [
        {
            "code": "0",
            "msg": "",
            "filename": "1D_16-35_1.jpg",
            "filesize": "196690",
            "width": "1024",
            "height": "682",
            "images":
            [
                {
                    "url": "fmn061/20111118",
                    "type": "large",
                    "width": "720",
                    "height": "479"
                },
                {
                    "url": "fmn061/20111118",
                    "type": "main",
                    "width": "200",
                    "height": "133"
                }
            ]
        }
    ]
}

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. int ParseJsonFromFile(const char* filename)  
  2. {  
  3.   // 解析json用Json::Reader  
  4.   Json::Reader reader;  
  5.   // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array...  
  6.   Json::Value root;         
  7.   
  8.   
  9.   std::ifstream is;  
  10.   is.open (filename, std::ios::binary );    
  11.   if (reader.parse(is, root))  
  12.   {  
  13.     std::string code;  
  14.     if (!root["files"].isNull())  // 访问节点,Access an object value by name, create a null member if it does not exist.  
  15.       code = root["uploadid"].asString();  
  16.       
  17.     // 访问节点,Return the member named key if it exist, defaultValue otherwise.  
  18.     code = root.get("uploadid", "null").asString();  
  19.   
  20.   
  21.     // 得到"files"的数组个数  
  22.     int file_size = root["files"].size();  
  23.   
  24.   
  25.     // 遍历数组  
  26.     for(int i = 0; i < file_size; ++i)  
  27.     {  
  28.       Json::Value val_image = root["files"][i]["images"];  
  29.       int image_size = val_image.size();  
  30.       for(int j = 0; j < image_size; ++j)  
  31.       {  
  32.         std::string type = val_image[j]["type"].asString();  
  33.         std::string url = val_image[j]["url"].asString();  
  34.       }  
  35.     }  
  36.   }  
  37.   is.close();  
  38.   return 0;  
  39. }  


3、在json结构中插入json

json中的数组,我一开始理解成跟c++中List,都是用下标去访问,但是这个中间有个问题:比如谁一个json的数字变量a,你要获取第一个数组中的元素给b,不能直接用b=a[0],而是得先定义一个int i=0;b=a[i],不然编译的时候会报错,不知道这是为什么,网上也没找到对应说明,如果哪位大神看到的话留言解答一下吧,谢谢~

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Json::Value arrayObj;   // 构建对象  
  2. Json::Value new_item, new_item1;  
  3. new_item["date"] = "2011-12-28";  
  4. new_item1["time"] = "22:30:36";  
  5. arrayObj.append(new_item);  // 插入数组成员  
  6. arrayObj.append(new_item1); // 插入数组成员  
  7. int file_size = root["files"].size();  
  8. for(int i = 0; i < file_size; ++i)  
  9.   root["files"][i]["exifs"] = arrayObj;   // 插入原json中  

4、输出 

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // 转换为字符串(带格式)  
  2. std::string out = root.toStyledString();  
  3. // 输出无格式json字符串  
  4. Json::FastWriter writer;  
  5. std::string out2 = writer.write(root);  

5、解析数组 

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. std::string strValue="{\"key1\":\"value1\",\"array\":[{\"key2\":\"value2\"},{\"key2\":\"value3\"},{\"key2\":\"value4\"}]}";     
  2.     Json::Reader reader;//json解析    
  3.     Json::Value value;//表示一个json格式的对象    
  4.     if(reader.parse(strValue,value))//解析出json放到json中区    
  5.     {    
  6.         std::string out=value["key1"].asString();    
  7.         std::cout<<out<<std::endl;    
  8.         const Json::Value arrayObj=value["array"];//迭代器    
  9.         for (int i=0; i < arrayObj.size();i++)      
  10.         {    
  11.             out=arrayObj[i]["key2"].asString();    
  12.             std::cout<<out;    
  13.             if(i!=arrayObj.size()-1)    
  14.                 std::cout<<std::endl;;    
  15.         }    
  16.     }    
不含迭代器的方法:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. string str = "[{"money":"100"},{"SB":"200"}]";  
  2.     Json::Reader reader;//json解析    
  3.     Json::Value value;//表示一个json格式的对象    
  4.         
  5.     if(reader.parse(str,value))//解析出json放到json中区    
  6.     {    
  7.         for(int i = 0;i<value.size();i++)  
  8.     {  
  9.         out=arrayObj[i]["SB"].asString();   
  10.     }  
  11.     }    
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值