数据格式在编程里面很常见,不同的系统都会有自己的标准。因为给有各的定义,每次做第三方开发系统对接的时候数据格式标准都是头疼的事情。

在开发过程中比较常见的比如有Json、 、Key-Value等。这里我们就先看看Json和 。两者的转换有很多开源的代码可以使用,而且也很完善,可以参考 2jsonxsltjson

在Json出现前应用很广泛,灵活性好,应用语言也没有限制,发展了这么长时间后 标准已经很臃肿。这里可以查看 的标准 标准。在C++里面解析和操作 的库也有不少,tiny 就是个不错的选择,体积少、简单、高效的开源库,现在已经发布了Tiny -2.

Json出来后立即被很多高级语言作为了标准推荐使用,如果想了解Json的定义请点击这里:JSON定义

2Json & Json2

接下来,我想做个简单的函数来转换。

< >
	<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>
</ >

上面的报文是在三方支付里面常见的报文,这次我们来实现对这段报文的Json格式的自由转换。

#include <string>
#include <iostream>
#include "tiny 2.h"
#include "nlohmann/json.hpp"

using json = nlohmann::json;
using namespace tiny 2;
using namespace std;

string  2json(string &src)
{
	 Document doc;
	doc.Parse( src.c_str() );
	
	json  root;
	 Element* rootElement = doc.RootElement();
	 Element* child = rootElement->FirstChildElement();
	while(child) {
		const char*   = child->Name() ;
		const char* value = child->GetText();
		child = child->NextSiblingElement();
		root[ ]=value ;
	}
	return  root.dump() ;
}

string json2 (string& src)
{
	 Document  Doc;
	 Node * pRoot =  Doc.NewElement(" ");
	 Doc.InsertFirstChild(pRoot);
	auto j3 = json::parse(src.c_str());
	for (json::iterator it = j3.begin(); it != j3.end(); ++it) {
		string key = it.key();
		string value = it.value() ;
		 Element * pElement =  Doc.NewElement(key.c_str()) ;
		pElement->SetText(value.c_str()) ;
		pRoot->InsertEndChild(pElement);
	}
	 Printer printer;
	pRoot->Accept( &printer );
	return printer.CStr();
}

int main()
{
	string src = "< >
				   <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>
				</ >" ;
	string json =  2json(src) ;
	string   = json2 (json) ;
	
	
	cout << json ;
	cout << endl ;
	cout <<   ;
}

这次我们使用tiny 2 和nlohmann json 做转换,需要将两者的头文件和源代码文件下载,并在编译中include。

nolhmann json 需要C++ 11 的支持,gcc版本需要在4.7以上。

可以使用下面命令编译:

g++ -std=c++11 json.cpp tiny 2.cpp -I./

./a.out
{"appid":"appid-value111111","mch_id":"mch_id-value22222","nonce_str":"nonce_str-value3333333","sign":"sign-value5555555555","transaction_id":"transaction_id-value44444444"}
< >
    <appid>appid-value111111</appid>
    <mch_id>mch_id-value22222</mch_id>
    <nonce_str>nonce_str-value3333333</nonce_str>
    <sign>sign-value5555555555</sign>
    <transaction_id>transaction_id-value44444444</transaction_id>
</ >
收藏 打印