数据格式在编程里面很常见,不同的系统都会有自己的标准。因为给有各的定义,每次做第三方开发系统对接的时候数据格式标准都是头疼的事情。
在开发过程中比较常见的比如有Json、XML、Key-Value等。这里我们就先看看Json和XML。两者的转换有很多开源的代码可以使用,而且也很完善,可以参考xml2json、xsltjson。
XML在Json出现前应用很广泛,灵活性好,应用语言也没有限制,发展了这么长时间后xml标准已经很臃肿。这里可以查看XML的标准XML标准。在C++里面解析和操作XML的库也有不少,tinyxml 就是个不错的选择,体积少、简单、高效的开源库,现在已经发布了TinyXml-2.
Json出来后立即被很多高级语言作为了标准推荐使用,如果想了解Json的定义请点击这里:JSON定义
XML2Json & Json2XML
接下来,我想做个简单的函数来转换。
?| 1 2 3 4 5 6 7 |
<xml>
<appid>appid-value111111</appid>
<mch_id>mch_id-value22222</mch_id>
<nonce_str>nonce_str-value3333333</nonce_str>
<transaction_id>transaction_id-value44444444</transaction_id>
<sign>sign-value5555555555</sign>
</xml>
|
上面的报文是在三方支付里面常见的报文,这次我们来实现对这段报文的Json格式的自由转换。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
#include <string>
#include <iostream>
#include "tinyxml2.h"
#include "nlohmann/json.hpp"
using json = nlohmann::json;
using namespace tinyxml2;
using namespace std;
string xml2json(string &src)
{
XMLDocument doc;
doc.Parse( src.c_str() );
json root;
XMLElement* rootElement = doc.RootElement();
XMLElement* child = rootElement->FirstChildElement();
while(child) {
const char* id="codetool">
|








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。