JSON与map 互转

DynamicStruct // 会排序 ,基于map
OrderedDynamicStruct / /不会排序 ,基于队列 dqueue

typedef Dynamic::Struct < std::string> DynamicStruct;

typedef Dynamic::Struct, Poco::OrderedSet< std::string>> OrderedDynamicStruct;

template , typename S = std::set>
class Struct

1、map2json 流程
map–>DynamicStruct 或 OrderedDynamicStruct -->调用tostring函数
//map2json

std::map<string, int> stMap;
	stMap["a1"] = 100;
	stMap["a2"] = 99;
	stMap["a0"] = 20;

    //存在map 和 ordermap 的构造函数
	DynamicStruct aStruct(stMap);
	cout << aStruct.toString() << endl;

	OrderedMap <string, int> st2Map;
	st2Map["a1"] = 100;
	st2Map["a2"] = 99;
	st2Map["a0"] = 20;

	OrderedDynamicStruct aStruct2(st2Map);
	cout << aStruct2.toString() << endl;

在这里插入图片描述

void VarTest::testStructToString()
{
     
	DynamicStruct aStruct;
	aStruct["First Name"] = "Junior";
	aStruct["Last Name"] = "POCO";
	aStruct["Age"] = 1;
	Var a1(aStruct);
	std::string res = a1.convert<std::string>();
	std::string expected = "{ \"Age\" : 1, \"First Name\" : \"Junior\", \"Last Name\" : \"POCO\" }";
	assertTrue (res == expected);
	assertTrue (aStruct.toString() == res);
}


void VarTest::testOrderedStructToString()
{
     
	OrderedDynamicStruct aStruct;
	aStruct["First Name"] = "Junior";
	aStruct["Last Name"] = "POCO";
	aStruct["Age"] = 1;
	Var a1(aStruct);
	std::string res = a1.convert<std::string>();
	std::string expected = "{ \"First Name\" : \"Junior\", \"Last Name\" : \"POCO\", \"Age\" : 1 }";
	assertTrue(res == expected);
	assertTrue(aStruct.toString() == res);
}

2、json2map 流程
json–>parser–>var -->var的函数 extract(可以为对象或数组)–> 转换成DynamicStruct 或 OrderedDynamicStruct --> 通过赋值给map

std::string json = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }";
Parser parser;
Var result;
try
{
     
	result = parser.parse(json);
}
catch (JSONException& jsone)
{
     
	std::cout << jsone.message() << std::endl;
}
//如果是对象的话,就使用这个 
Object::Ptr object = result.extract<Object::Ptr>();
//下面之所以能够这样做,因为重载了 Poco::OrderedDynamiStruct 和  const Poco::DynamicStruct& (),
//可以可以赋值
//,C++中没有返回类型的函数有3个,构造函数、析构函数、类型转换函数
const DynamicStruct &ds = *object;   
std::map<string, Var> st3Map;
Object::ConstIterator iter = ds.begin();
for (; iter != ds.end(); ++iter)
{
     
	const string& key = iter->first;
	const Var& var    = iter->second ;
    //在这里转换
	st3Map[key] = var;
}

for (auto& m : st3Map)
{
     
	cout << m.first << ": " << m.second.toString() << endl ;
}

你可能感兴趣的:(map,windows)