Poco Json使用示例

#include "Poco/JSON/JSON.h"
#include "Poco/JSON/Array.h"
#include "Poco/JSON/Parser.h"
#include "Poco/JSON/ParseHandler.h"
#include 

using Poco::JSON::Object;
using Poco::JSON::Array;
using Poco::JSON::ParseHandler;
using Poco::JSON::Parser;
/*
{
"name" : "Franky"
"children" : 
	[ 
		"Jonas",
		"Ellen"
	], 
"address": { 
	"street": "A Street", 
	"number": 123, 
	"city":"The City"
 } 
}
*/
std::string jsons = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ], \
					\"address\": { \"street\": \"A Street\", \"number\": 123, \"city\":\"The City\"} }";
int main(int args, char* argv[])
{
	/* parse json */
	Object::Ptr json;
	Parser parser;
	Poco::Dynamic::Var object;
	try
	{
		object = parser.parse(jsons);
	}
	catch (Poco::JSON::JSONException& e)
	{
		std::cout << e.message() << std::endl;
		_ASSERT(false);
	}

	Object::Ptr jObj = object.extract<Object::Ptr>();
	if (jObj)
	{
		Poco::Dynamic::Var name = jObj->get("name");
		if (name.isString())
		{
			std::cout << "name: " << name.convert<std::string>() << std::endl;
		}

		if (jObj->isArray("children"))
		{
			Poco::JSON::Array::Ptr pArray = jObj->getArray("children");
			std::cout << "children[0]: " << pArray->get(0).convert<std::string>() << std::endl;			
			std::cout << "children[1]: " << pArray->get(1).convert<std::string>() << std::endl;			
			std::cout << "children[0]: " << pArray->getElement<std::string>(0) << std::endl;
			std::cout << "children[1]: " << pArray->getElement<std::string>(1) << std::endl;
		}

		if (jObj->isObject("address"))
		{
			Object::Ptr pObject = jObj->getObject("address");
			if (pObject->has("street"))
			{
				std::cout << "street: " << pObject->get("street").convert<std::string>() << std::endl;
			}
			if (pObject->has("city"))
			{
				std::cout << "city: " << pObject->get("city").convert<std::string>() << std::endl;
			}
			if (pObject->has("number"))
			{
				std::cout << "number: " << (Poco::UInt32)pObject->get("number") << std::endl;
				std::cout << "number: " << pObject->get("number").convert<Poco::UInt32>() << std::endl;
			}
		 }
	}

	// construct json
	Object newObj;
	newObj.set("name", "fruit");
	newObj.set("number", 3);
	
	Array fArr;
	Object orange;
	orange.set("name", "orange");
	orange.set("color", "orange");
	fArr.add(orange);
	Object apple;
	apple.set("name", "apple");
	apple.set("color", "red");
	fArr.add(apple);
	Object strawberry;
	strawberry.set("name", "strawberry");
	strawberry.set("color", "red");
	fArr.add(strawberry);

	newObj.set("fruits", fArr);

	std::stringstream os;
	//Poco::JSON::Stringifier::stringify(newObj, os);
	newObj.stringify(os);
	std::cout << os.str() << std::endl;
	
	return 0;
}

你可能感兴趣的:(poco,c++,tool,poco,json)