C++解析JSON之JsonCPP

一、JSON简介

JSON全称为JavaScript ObjectNotation,它是一种轻量级的数据交换格式,易于阅读、编写、解析。

JSON由两种基本结构构成:

1"名称/"对的集合,可以理解为对象。

2)值的组合,可以理解为数组。

JSON对象简单示例

示例1

{

   "header": {

     "pid": "10",

     "cas": "1"

   },

   "body": {

     "bodyCode": "JSON",

     "bodyName":"JavaScriptObject Notation",

     "GUId": "1"

   }

}

示例2

{

   "header": {

     "pid": "10",

     "cas": "1"

   },

   "ack": [{

     "ackCode": "JSON",

     "ackName":"JavaScript ObjectNotation",

   },{

     "ackCode": "JSON",

     "ackName":"JavaScript ObjectNotation",

   }

   "GUId":"1"

}

JSON更详细的介绍请看官网:http://www.json.org

二、JSONCPP

1.     JsonCPP简介

      jsoncppc++解析JSON串常用的解析库之一。其常用的类有:

a)     Json::Value     可以表示里所有的类型,比如int,string,object,array等,其支持的类型可以参考Json:ValueType中的值。

b)     Json::Reader   json文件流或字符串解析到Json::Value,主要函数有Parse

c)     Json::Writer    Json::Reader相反,将Json::Value转化成字符串流,注意它的两个子类:Json::FastWriterJson::StyleWriter,分别输出不带格式的json和带格式的json

d)     Json::Value::Members 主要用于以STL风格解析JSON数组。看过源代码的人已知道,Members其实是typedefvector<string>而已。

2.     JSONCPP解析示例

a)    解析JSON串格式

{

  "JsonID" : "BD6D7FDA-54D2-468b-A3DE-9D5FBDB78207",

  "Send" : {

     "ID" : "B8E09E97-F379-4bb0-814A-389FD3F66631",

     "Items" : [

        {

           "Count" : 2,

           "Code" : "0101",

           "X" : 1,

           "Y" : 2

        },

        {

           "Count" : 2,

           "Code" : "0101",

           "X" : 1,

           "Y" : 2

        }

      ]

   }

}

b)    生成的JSON

{

  "Ack" : [

      {

        "ActualCount" : 2,

        "Code" : "0101"

     },

      {

        "ActualCount" : 2,

        "Code" : "0101"

      }

   ],

  "JsonID" : "BD6D7FDA-54D2-468b-A3DE-9D5FBDB78207"

}

 

c)        解析、生成JSON代码

需要引入的.h文件

[html]  view plain copy
  1. #pragma once  
  2. #pragma comment(lib, "json_vc71_libmtd.lib")  
  3.    
  4. #include "json/json.h"  

实现

[cpp]  view plain copy
  1. void CJSONTestDlg::OnBnClickedButton1()  
  2. {  
  3.     CEdit* pEdit =(CEdit*)GetDlgItem(IDC_EDIT1);  
  4.     CString str;   
  5.     pEdit->GetWindowText(str); //str即为a)中定义的JSON串  
  6.     pEdit->FmtLines(true);  
  7.   
  8.     Json::Reader reader;  
  9.     Json::Value root;  
  10.   
  11.     if (reader.parse(WC2UT(str.GetBuffer(0)), root))  // reader将Json字符串解析到root,root将包含Json里所有子元素  
  12.     {  
  13.         std::string JsonID = root["JsonID"].asString();   
  14.         Json::Value rtnRoot;  
  15.         rtnRoot["JsonID"]=JsonID;  
  16.   
  17.         Json::Value ack;  
  18.         Json::Value send = root["Send"];  
  19.         if(!send["Items"].isNull()){  
  20.             Json::Value Items = send["Items"];  
  21.             int sendSize = Items.size();  
  22.   
  23.             for(int i=0;i<sendSize;i++){//循环获取到JSON串数组当中的值  
  24.                 std::string  Code = Items[i]["Code"].asString();  
  25.                 int x = Items[i]["X"].asInt();  
  26.                 int y = Items[i]["Y"].asInt();  
  27.                 int count = Items[i]["Count"].asInt();  
  28.                   
  29.                 //更具读到的JSON串中的值生成所需内容  
  30.                 Json::Value newAckItem;  
  31.                 newAckItem["Code"]=Code;  
  32.                 newAckItem["ActualCount"]=count;  
  33.   
  34.                 ack.append(newAckItem);  
  35.             }  
  36.         }  
  37.         rtnRoot["Ack"]=ack;  
  38.         std::string rtnOut = rtnRoot.toStyledString();//生成带格式的JSON串  
  39. #ifdef UNICODE  
  40.         std::wstring stemp = s2ws(rtnOut);   
  41.         LPCWSTR result = stemp.c_str();  
  42. #else  
  43.         LPCWSTR result = rtnOut.c_str();  
  44. #endif  
  45.         MessageBox(result,_T("根据JSON串,生成的对应JSON串信息"));  
  46.         CEdit* pEdit =(CEdit*)GetDlgItem(IDC_EDIT2);     
  47.         pEdit->SetWindowText(result);    
  48.     }else{  
  49.         CEdit* pRtnEdit =(CEdit*)GetDlgItem(IDC_EDIT2);     
  50.         pRtnEdit->SetWindowText(_T("JSON格式错误"));    
  51.     }  
  52. }  

 

将JSONCPP以静态库方式导入,需要注意项目中的代码生成中的运行库,和JSONCPP的静态库项目的代码生成的运行库要一致,否则将报如下错误

afxver_.h(81): fatal error C1189: #error :  Please use the /MD switch for _AFXDLL builds

项目中的Runtime Library需设置的一样

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值