当前位置: 首页>>代码示例>>C++>>正文


C++ JSONNode::at方法代码示例

本文整理汇总了C++中JSONNode::at方法的典型用法代码示例。如果您正苦于以下问题:C++ JSONNode::at方法的具体用法?C++ JSONNode::at怎么用?C++ JSONNode::at使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在JSONNode的用法示例。


在下文中一共展示了JSONNode::at方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: response

void Endpoint_v1::TicketRequest::onRequestFinished()
{
	QByteArray respbytes = reply->readAll();
	reply->deleteLater();
	std::string response ( respbytes.begin(), respbytes.end() );

	JSONNode respnode = libJSON::parse ( response );
	JSONNode errnode = respnode.at ( "error" );
	if (errnode.as_string() != "") {
		emit failed(QString("server_failure"), QString(errnode.as_string().c_str()));
		return;
	}

	available = FHttpApi::Data_GetTicketDefault;

	JSONNode subnode = respnode.at ("ticket");
	ticket = new Ticket();
	ticket->ticket = subnode.as_string().c_str();
	ticket->name = _un;
	ticket->password = _p;

	subnode = respnode.at("default_character");
	defaultCharacter = subnode.as_string().c_str();

	subnode = respnode.at("characters");
	qslFromJsonArray(subnode, characters);

	subnode = respnode.at("bookmarks");
	qslFromJsonArray(subnode, bookmarks);

	emit succeeded();
}
开发者ID:AerysBat,项目名称:flist-messenger,代码行数:32,代码来源:endpoint_v1.cpp

示例2: RequestAccountInfo

void CDropbox::RequestAccountInfo()
{
	MCONTACT hContact = CDropbox::GetDefaultContact();

	ptrA token(db_get_sa(NULL, MODULE, "TokenSecret"));
	GetAccountInfoRequest request(token);
	NLHR_PTR response(request.Send(hNetlibConnection));
	HandleHttpResponseError(response);

	JSONNode root = JSONNode::parse(response->pData);
	if (root.empty())
		return;

	JSONNode referral_link = root.at("referral_link");
	if (!referral_link.empty())
		db_set_s(hContact, MODULE, "Homepage", referral_link.as_string().c_str());

	JSONNode display_name = root.at("display_name");
	if (!display_name.empty())
	{
		ptrT display_name(mir_utf8decodeT(display_name.as_string().c_str()));
		TCHAR *sep = _tcsrchr(display_name, _T(' '));
		if (sep)
		{
			db_set_ts(hContact, MODULE, "LastName", sep + 1);
			display_name[mir_tstrlen(display_name) - mir_tstrlen(sep)] = '\0';
			db_set_ts(hContact, MODULE, "FirstName", display_name);
		}
		else
		{
			db_set_ts(hContact, MODULE, "FirstName", display_name);
			db_unset(hContact, MODULE, "LastName");
		}
	}

	JSONNode country = root.at("country");
	if (!country.empty())
	{
		std::string isocode = country.as_string();

		if (isocode.empty())
			db_unset(hContact, MODULE, "Country");
		else
		{
			char *country = (char *)CallService(MS_UTILS_GETCOUNTRYBYISOCODE, (WPARAM)isocode.c_str(), 0);
			db_set_s(hContact, MODULE, "Country", country);
		}
	}

	JSONNode quota_info = root.at("quota_info");
	if (!quota_info.empty())
	{
		db_set_dw(hContact, MODULE, "SharedQuota", quota_info.at("shared").as_int());
		db_set_dw(hContact, MODULE, "NormalQuota", quota_info.at("normal").as_int());
		db_set_dw(hContact, MODULE, "TotalQuota", quota_info.at("quota").as_int());
	}
}
开发者ID:kmdtukl,项目名称:miranda-ng,代码行数:57,代码来源:dropbox.cpp

示例3: main

int main(){
JSONNode n = read_formatted("input.json");
JSONNode n1 = read_formatted("input1.json");
test *tst = new test();
int status;
//n.set_name(abi::__cxa_demangle(typeid(*tst).name(), 0,0,&status ));
n.push_back(JSONNode("FF::Node_Subclass", abi::__cxa_demangle(typeid(*tst).name(), 0,0,&status )));
if(n1.type()==JSON_NULL){
   std::cout<<"null"<<std::endl; 
}
JSONNode n2 (JSON_NODE);
n2.set_name("Child1");
n2.push_back(JSONNode("id",1));
n.set_name("Parrent");
n.push_back(n2);
JSONNode::iterator it =n.find_nocase("String Node");
if(it->as_string()=="-1"){std::cout<<it->as_int()<<std::endl;}
it->as_int()!=-1 ? (std::cout<< "it is"<<std::endl) : (std::cout<<"Mapper Warning: processor id is -1"<<std::endl);
if (n.at("String Node")==""){
std::cout<<"ha ha ha"<<std::endl;
}
std::cout<< "This is the name: "<<n.name()<<std::endl;
n.at("String Node")="";
bool x =true;
n.push_back(JSONNode("MyBOOLNODE", x));
n["String Node"]=x;
//n.erase(n.find_nocase("String Node"));
write_formatted(n1, "out1.json");
write_formatted(n, "out.json");
JSONNode::const_iterator i =n.find_nocase("ArrayOfNumbers");
std::string strLowerCase= "ARRAYOfNUMbers"; 
std::string myTest= "ff::ff_farm<adaptive_loadbalancer, ff::ff_gatherer>";
std::transform(myTest.begin(), myTest.end(), myTest.begin(), ::tolower);
std::size_t found = myTest.find("adaptive_loadbalancer");
if (found!=std::string::npos)
  std::cout << "first 'needle' found at: " << found << '\n';

std::cout<< "here it is: " << myTest<< std::endl;
JSONNode n_ar = n.at("ArrayOfNumbers");
std::cout<<"here :"<<n_ar[0].as_int()<< std::endl;
// if (0 == strcasecmp("hello", "HELLO"))

if(strcasecmp((i->name()).c_str(), strLowerCase.c_str()) == 0)
//if(!(n2.empty()))
  std::cout<<"haha"<<i->size()<<std::endl;
std::cout<<i->name()<<std::endl;
std::cout<<((i->as_array()).begin()+1)->as_int()<<std::endl;
std::cout<<((i->as_array()).at(1)).as_int()<<std::endl;
std::cout<<((i->as_array())[1]).as_int()<<std::endl;
//std::cout<<i->as_string()<<std::endl;
//JSONNode c(JSON_ARRAY);
//c=i->as_array();
//JSONNode nk= c.at(0);
//JSONNode::const_iterator it = c.begin();
//std::cout <<nk.as_int()<<std::endl;
return 0;
}
开发者ID:mehdi-goli,项目名称:MC-FastFlow-PEI,代码行数:57,代码来源:test_parser.cpp

示例4: RequestAccountInfo

void CDropbox::RequestAccountInfo()
{
	MCONTACT hContact = CDropbox::GetDefaultContact();

	ptrA token(db_get_sa(NULL, MODULE, "TokenSecret"));
	GetAccountInfoRequest request(token);
	NLHR_PTR response(request.Send(hNetlibConnection));
	HandleHttpResponseError(response);

	JSONNode root = JSONNode::parse(response->pData);
	if (root.empty())
		return;

	JSONNode referral_link = root.at("referral_link");
	if (!referral_link.empty())
		db_set_s(hContact, MODULE, "Homepage", referral_link.as_string().c_str());

	JSONNode display_name = root.at("display_name");
	if (!display_name.empty())
	{
		CMString tszDisplayName(display_name.as_mstring());
		int pos = tszDisplayName.ReverseFind(' ');
		if (pos != -1)
		{
			db_set_ts(hContact, MODULE, "LastName", tszDisplayName.Mid(pos+1));
			db_set_ts(hContact, MODULE, "FirstName", tszDisplayName.Left(pos));
		}
		else
		{
			db_set_ts(hContact, MODULE, "FirstName", tszDisplayName);
			db_unset(hContact, MODULE, "LastName");
		}
	}

	JSONNode country = root.at("country");
	if (!country.empty())
	{
		std::string isocode = country.as_string();

		if (isocode.empty())
			db_unset(hContact, MODULE, "Country");
		else
		{
			char *szCountry = (char *)CallService(MS_UTILS_GETCOUNTRYBYISOCODE, (WPARAM)isocode.c_str(), 0);
			db_set_s(hContact, MODULE, "Country", szCountry);
		}
	}

	JSONNode quota_info = root.at("quota_info");
	if (!quota_info.empty())
	{
		db_set_dw(hContact, MODULE, "SharedQuota", quota_info.at("shared").as_int());
		db_set_dw(hContact, MODULE, "NormalQuota", quota_info.at("normal").as_int());
		db_set_dw(hContact, MODULE, "TotalQuota", quota_info.at("quota").as_int());
	}
}
开发者ID:gloria8023,项目名称:miranda-ng,代码行数:56,代码来源:dropbox.cpp

示例5: CommandDelete

void CDropbox::CommandDelete(void *arg)
{
	CommandParam *param = (CommandParam*)arg;

	char *path = (char*)param->data;
	if (path == NULL) {
		CMStringA error(FORMAT, T2Utf(TranslateT("\"%s\" command has invalid parameter.\nUse \"/help\" for more info.")), "/delete");
		ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0);
		CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)error.GetBuffer());

		return;
	}
	ptrA token(db_get_sa(NULL, MODULE, "TokenSecret"));
	ptrA encodedPath(mir_utf8encode(path));
	DeleteRequest request(token, encodedPath);
	NLHR_PTR response(request.Send(param->instance->hNetlibConnection));

	if (response == NULL || response->resultCode != HTTP_STATUS_OK) {
		ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0);
		return;
	}

	JSONNode root = JSONNode::parse(response->pData);
	if (root.empty()) {
		ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0);
		return;
	}

	bool isDeleted = root.at("is_deleted").as_bool();
	CMStringA message(FORMAT, "%s %s", path, !isDeleted ? T2Utf(TranslateT("is not deleted")) : T2Utf(TranslateT("is deleted")));
	ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0);
	CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)message.GetBuffer());
}
开发者ID:kxepal,项目名称:miranda-ng,代码行数:33,代码来源:dropbox_commands.cpp

示例6: CommandShare

void CDropbox::CommandShare(void *arg)
{
	CommandParam *param = (CommandParam*)arg;

	char *path = (char*)param->data;
	if (path == NULL) {
		CMStringA error(FORMAT, T2Utf(TranslateT("\"%s\" command has invalid parameter.\nUse \"/help\" for more info.")), "/share");
		ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0);
		CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)error.GetBuffer());

		return;
	}

	ptrA token(db_get_sa(NULL, MODULE, "TokenSecret"));
	ptrA encodedPath(mir_utf8encode(path));
	bool useShortUrl = db_get_b(NULL, MODULE, "UseSortLinks", 1) > 0;
	ShareRequest request(token, encodedPath, useShortUrl);
	NLHR_PTR response(request.Send(param->instance->hNetlibConnection));

	if (response == NULL || response->resultCode != HTTP_STATUS_OK) {
		ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0);
		return;
	}

	JSONNode root = JSONNode::parse(response->pData);
	if (root.empty()) {
		ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0);
		return;
	}

	CMStringA link = root.at("url").as_string().c_str();
	ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0);
	CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)link.GetBuffer());
}
开发者ID:kxepal,项目名称:miranda-ng,代码行数:34,代码来源:dropbox_commands.cpp

示例7: CommandContent

void CDropbox::CommandContent(void *arg)
{
	CommandParam *param = (CommandParam*)arg;

	char *path = (char*)param->data;
	if (path == NULL)
		path = "";

	ptrA token(db_get_sa(NULL, MODULE, "TokenSecret"));
	ptrA encodedPath(mir_utf8encode(path));
	GetMetadataRequest request(token, encodedPath);
	NLHR_PTR response(request.Send(param->instance->hNetlibConnection));

	if (response == NULL || response->resultCode != HTTP_STATUS_OK) {
		ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0);
		return;
	}

	JSONNode root = JSONNode::parse(response->pData);
	if (root.empty()) {
		ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0);
		return;
	}

	CMStringA message;
	bool isDir = root.at("is_dir").as_bool();
	if (!isDir)
		message.AppendFormat("\"%s\" %s", encodedPath, T2Utf(TranslateT("is file")));
	else {
		JSONNode content = root.at("contents").as_array();
		for (size_t i = 0; i < content.size(); i++) {
			JSONNode item = content[i];
			if (item.empty()) {
				if (i == 0)
					message.AppendFormat("\"%s\" %s", encodedPath, T2Utf(TranslateT("is empty")));
				break;
			}

			CMStringA subName(item.at("path").as_string().c_str());
			message.AppendFormat("%s\n", (subName[0] == '/') ? subName.Mid(1) : subName);
		}
	}

	ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0);
	CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)message.GetBuffer());
}
开发者ID:kxepal,项目名称:miranda-ng,代码行数:46,代码来源:dropbox_commands.cpp

示例8: trades

//------------------------------------------------------------------------------
// downloads recent trade data:
std::string KClient::trades(const std::string& pair, 
			    const std::string& since,
			    std::vector<KTrade>& output)
{
   KInput ki;
   ki["pair"] = pair;
   ki["since"] = since;

   // download and parse data
   json_string data = libjson::to_json_string( public_method("Trades", ki) ); 
   JSONNode root = libjson::parse(data);



   // throw an exception if there are errors in the JSON response
   if (!root.at("error").empty()) {
      std::ostringstream oss;
      oss << "Kraken response contains errors: ";
      
      // append errors to output string stream
      for (JSONNode::const_iterator
	      it = root["error"].begin(); it != root["error"].end(); ++it) 
	 oss << std::endl << " * " << libjson::to_std_string(it->as_string());
      
      throw std::runtime_error(oss.str());
   }

   // throw an exception if result is empty   
   if (root.at("result").empty()) {
      throw std::runtime_error("Kraken response doesn't contain result data");
   }



   JSONNode &result = root["result"];
   JSONNode &result_pair = result[0];
   std::string last = libjson::to_std_string( result.at("last").as_string() );

   std::vector<KTrade> buf;
   for (JSONNode::const_iterator 
	   it = result_pair.begin(); it != result_pair.end(); ++it)
      buf.push_back(KTrade(*it));
      
   output.swap(buf);
   return last;
}
开发者ID:erdincay,项目名称:krakenapi,代码行数:48,代码来源:kclient.cpp

示例9: processMessage

bool USB_device::processMessage(ClientConn& client, string& cmd, JSONNode& n){
	if (cmd == "controlTransfer"){
		unsigned id = jsonIntProp(n, "id", 0);
		uint8_t bmRequestType = jsonIntProp(n, "bmRequestType", 0xC0);
		uint8_t bRequest = jsonIntProp(n, "bRequest");
		uint16_t wValue = jsonIntProp(n, "wValue", 0);
		uint16_t wIndex = jsonIntProp(n, "wIndex", 0);
	
		bool isIn = bmRequestType & 0x80;
		
		JSONNode reply(JSON_NODE);
		reply.push_back(JSONNode("_action", "return"));
		reply.push_back(JSONNode("id", id));
		
		int ret = -1000;
		
		if (isIn){
			uint16_t wLength = jsonIntProp(n, "wLength", 64);
			if (wLength > 64) wLength = 64;
			if (wLength < 0) wLength = 0;
		
			uint8_t data[wLength];
			ret = controlTransfer(bmRequestType, bRequest, wValue, wIndex, data, wLength);
			
			if (ret >= 0){
				JSONNode data_arr(JSON_ARRAY);
				for (int i=0; i<ret && i<wLength; i++){
					data_arr.push_back(JSONNode("", data[i]));
				}
				data_arr.set_name("data");
				reply.push_back(data_arr);
			}
		}else{
			string datastr;
			JSONNode data = n.at("data");
			if (data.type() == JSON_ARRAY){
				for(JSONNode::iterator i=data.begin(); i!=data.end(); i++){
					datastr.push_back(i->as_int());
				}
			}else{
				datastr = data.as_string();
			}
			ret = controlTransfer(bmRequestType, bRequest, wValue, wIndex, (uint8_t *)datastr.data(), datastr.size());
		}
		
		reply.push_back(JSONNode("status", ret));
	
		client.sendJSON(reply);
	}else if(cmd == "enterBootloader"){
		std::cout << "enterBootloader: ";
		int r = controlTransfer(0x40|0x80, 0xBB, 0, 0, NULL, 100);
		std::cout << "return " <<  r << std::endl;
	}else{
		return false;
	}
	return true;
}
开发者ID:nonolith,项目名称:connect,代码行数:57,代码来源:usb.cpp

示例10: getIntFromArray

int getIntFromArray(JSONNode node, char* name) {
  try {
	  return node.at(name).as_array()[0].as_int();

    } catch(exception& e) {
		cout << " Parse error" << e.what() << endl; 
    }
	return -65535;
}
开发者ID:Jackchen0808,项目名称:Operator-Console,代码行数:9,代码来源:jsonhelpers.cpp

示例11: RequestAccountInfo

void CDropbox::RequestAccountInfo(void *p)
{
	CDropbox *self = (CDropbox*)p;

	MCONTACT hContact = self->GetDefaultContact();

	ptrA token(db_get_sa(NULL, MODULE, "TokenSecret"));
	GetCurrentAccountRequest request(token);
	NLHR_PTR response(request.Send(self->hNetlibConnection));
	HandleJsonResponseError(response);

	JSONNode root = JSONNode::parse(response->pData);
	if (root.empty())
		return;

	JSONNode referral_link = root.at("referral_link");
	if (!referral_link.empty())
		db_set_s(hContact, MODULE, "Homepage", referral_link.as_string().c_str());

	JSONNode email = root.at("email");
	if (!email.empty())
		db_set_s(hContact, MODULE, "e-mail", email.as_string().c_str());

	JSONNode name = root.at("name");
	if (!name.empty()) {
		db_set_utf(hContact, MODULE, "FirstName", name.at("given_name").as_string().c_str());
		db_set_utf(hContact, MODULE, "LastName", name.at("surname").as_string().c_str());
	}

	JSONNode country = root.at("country");
	if (!country.empty()) {
		std::string isocode = country.as_string();

		if (isocode.empty())
			db_unset(hContact, MODULE, "Country");
		else {
			char *szCountry = (char *)CallService(MS_UTILS_GETCOUNTRYBYISOCODE, (WPARAM)isocode.c_str(), 0);
			db_set_s(hContact, MODULE, "Country", szCountry);
		}
	}

	/*JSONNode quota_info = root.at("quota_info");
	if (!quota_info.empty()) {
		ULONG lTotalQuota = quota_info.at("quota").as_int();
		ULONG lNormalQuota = quota_info.at("normal").as_int();
		ULONG lSharedQuota = quota_info.at("shared").as_int();

		db_set_dw(hContact, MODULE, "SharedQuota", lSharedQuota);
		db_set_dw(hContact, MODULE, "NormalQuota", lNormalQuota);
		db_set_dw(hContact, MODULE, "TotalQuota", lTotalQuota);

		db_set_s(hContact, "CList", "StatusMsg", CMStringA(FORMAT, Translate("Free %ld of %ld MB"), (lTotalQuota - lNormalQuota) / (1024 * 1024), lTotalQuota / (1024 * 1024)));
	}*/
}
开发者ID:ybznek,项目名称:miranda-ng,代码行数:54,代码来源:dropbox.cpp

示例12: handle_admin

bool ServerSocket::handle_admin(JSONNode& n)
{
    is_admin = true;
    string cmd = n.at("cmd").as_string();
    if(cmd == "_connect")
    {
        return(true);
    }
    else if(cmd == "_users")
    {
        return(handle_admin_users());
    }
    else if(cmd == "_stats")
    {
        return(handle_admin_stats());
    }
    else if(cmd == "_stop")
    {
        return(handle_admin_stop());
    }
    return(true);
}
开发者ID:AnthonyMyatt,项目名称:IRC-2-HTTP,代码行数:22,代码来源:ServerSocket.cpp

示例13: HandleJsonResponseError

void CDropbox::HandleJsonResponseError(NETLIBHTTPREQUEST *response)
{
	if (response == NULL)
		throw DropboxException(HttpStatusToText(HTTP_STATUS_ERROR));

	if (response->resultCode == HTTP_STATUS_OK)
		return;

	if (response->resultCode != HTTP_STATUS_CONFLICT) {
		if (response->dataLength)
			throw DropboxException(response->pData);
		throw DropboxException(HttpStatusToText((HTTP_STATUS)response->resultCode));
	}

	JSONNode root = JSONNode::parse(response->pData);
	if (root.empty())
		throw DropboxException(HttpStatusToText(HTTP_STATUS_ERROR));

	JSONNode error = root.at("error_summary");
	if (error.empty())
		return;

	throw DropboxException(error.as_string().c_str());
}
开发者ID:wyrover,项目名称:miranda-ng,代码行数:24,代码来源:dropbox_utils.cpp

示例14: TestInspectors

void TestSuite::TestInspectors(void){
    UnitTest::SetPrefix("TestInspectors.cpp - Inspectors");
    JSONNode test = JSONNode(JSON_NULL);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_string(), JSON_TEXT(""));
	   assertEquals(test.as_int(), 0);
	   assertEquals(test.as_float(), 0.0f);
	   assertEquals(test.as_bool(), false);
    #endif

    test = 15.5f;
    assertEquals(test.type(), JSON_NUMBER);
  #ifdef JSON_CASTABLE
    assertEquals(test.as_string(), JSON_TEXT("15.5"));
  #endif
    assertEquals(test.as_int(), 15);
    assertEquals(test.as_float(), 15.5f);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_bool(), true);
    #endif

    test = 0.0f;
    assertEquals(test.type(), JSON_NUMBER);
  #ifdef JSON_CASTABLE
    assertEquals(test.as_string(), JSON_TEXT("0"));
  #endif
    assertEquals(test.as_int(), 0);
    assertEquals(test.as_float(), 0.0f);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_bool(), false);
    #endif

    test = true;
    assertEquals(test.type(), JSON_BOOL);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_string(), JSON_TEXT("true"));
	   assertEquals(test.as_int(), 1);
	   assertEquals(test.as_float(), 1.0f);
    #endif
    assertEquals(test.as_bool(), true);

    test = false;
    assertEquals(test.type(), JSON_BOOL);
    #ifdef JSON_CASTABLE
	   assertEquals(test.as_string(), JSON_TEXT("false"));
	   assertEquals(test.as_int(), 0);
	   assertEquals(test.as_float(), 0.0f);
    #endif
    assertEquals(test.as_bool(), false);

    #ifdef JSON_CASTABLE
	   test.cast(JSON_NODE);
    #else
	   test = JSONNode(JSON_NODE);
    #endif
    assertEquals(test.type(), JSON_NODE);
    assertEquals(test.size(), 0);
    test.push_back(JSONNode(JSON_TEXT("hi"), JSON_TEXT("world")));
    test.push_back(JSONNode(JSON_TEXT("hello"), JSON_TEXT("mars")));
    test.push_back(JSONNode(JSON_TEXT("salut"), JSON_TEXT("france")));
    assertEquals(test.size(), 3);
    TestSuite::testParsingItself(test);

    #ifdef JSON_CASTABLE
	   JSONNode casted = test.as_array();
	   #ifdef JSON_UNIT_TEST
		  assertNotEquals(casted.internal, test.internal);
	   #endif
	   assertEquals(casted.type(), JSON_ARRAY);
	   assertEquals(test.type(), JSON_NODE);
	   assertEquals(test.size(), 3);
	   assertEquals(casted.size(), 3);
	   TestSuite::testParsingItself(casted);
    #endif

    UnitTest::SetPrefix("TestInspectors.cpp - Location");

    try {
	   #ifdef JSON_CASTABLE
		  assertEquals(casted.at(0), JSON_TEXT("world"));
		  assertEquals(casted.at(1), JSON_TEXT("mars"));
		  assertEquals(casted.at(2), JSON_TEXT("france"));
		  assertEquals(casted.at(0).name(), JSON_TEXT(""));
		  assertEquals(casted.at(1).name(), JSON_TEXT(""));
		  assertEquals(casted.at(2).name(), JSON_TEXT(""));
	   #endif
	   assertEquals(test.at(0), JSON_TEXT("world"));
	   assertEquals(test.at(1), JSON_TEXT("mars"));
	   assertEquals(test.at(2), JSON_TEXT("france"));
	   assertEquals(test.at(0).name(), JSON_TEXT("hi"));
	   assertEquals(test.at(1).name(), JSON_TEXT("hello"));
	   assertEquals(test.at(2).name(), JSON_TEXT("salut"));
    } catch (std::out_of_range){
	   FAIL("exception caught");
    }

    try {
	   assertEquals(test.at(JSON_TEXT("hi")), JSON_TEXT("world"));
	   assertEquals(test.at(JSON_TEXT("hello")), JSON_TEXT("mars"));
	   assertEquals(test.at(JSON_TEXT("salut")), JSON_TEXT("france"));
//.........这里部分代码省略.........
开发者ID:NatalieWolfe,项目名称:libjson,代码行数:101,代码来源:TestInspectors.cpp

示例15: dbfs

TEST_F(SerializerUnittest, Write)
{
    Serializer serializer;
    serializer.Init(".", "Data", SerializerOpenModeWrite);

    // Create 4D field with JILK storage plus stride 2
    const int isize = 6, jsize = 8, ksize = 7, lsize = 4;
    const int kstride = 2, lstride = kstride*ksize, istride = lstride*lsize, jstride = istride*isize;
    const int ibstrided = istride*sizeof(double), jbstrided = jstride*sizeof(double),
              kbstrided = kstride*sizeof(double), lbstrided = lstride*sizeof(double);
    const int ibstridef = istride*sizeof(float), jbstridef = jstride*sizeof(float),
              kbstridef = kstride*sizeof(float), lbstridef = lstride*sizeof(float);
    const int allocsize = jstride*jsize;
    std::vector<double> dataD(allocsize);
    std::vector<float> dataF(allocsize);

    for (int i = 0; i < isize; ++i)
        for (int j = 0; j < jsize; ++j)
            for (int k = 0; k < ksize; ++k)
                for (int l = 0; l < lsize; ++l)
                {
                    dataD[i*istride + j*jstride + k*kstride + l*lstride]
                        = i*12.25 + j*k*1. - 2.75 / (l+10.);
                    dataF[i*istride + j*jstride + k*kstride + l*lstride]
                        = i*12.25 + j*k*1. - 2.75 / (l+10.);
                }

    // Register various versions of this field
    serializer.RegisterField("ik"  , "double", 8, isize,     1, ksize,     1, 0, 0, 0, 0, 0, 0, 0, 0);
    serializer.RegisterField("jk"  , "float" , 4,     1, jsize, ksize,     1, 0, 0, 0, 0, 0, 0, 0, 0);
    serializer.RegisterField("ikl" , "double", 8, isize,     1, ksize, lsize, 0, 0, 0, 0, 0, 0, 0, 0);
    serializer.RegisterField("ijkl", "float" , 4, isize, jsize, ksize, lsize, 0, 0, 0, 0, 0, 0, 0, 0);

    // Setting a savepoint and serializing all fields
    Savepoint sp;
    sp.Init("MySavepoint");
    sp.AddMetainfo("Value", 3.125);
    sp.AddMetainfo("ValueF", 3.625f);
    sp.AddMetainfo("MyName", "Andrea Arteaga");
    sp.AddMetainfo("MyAge", 26);
    sp.AddMetainfo("ILikeThis", true);

    const int ilevel = 3, jlevel = 0, llevel = 2;

    const double*   pIKData = dataD.data() + jstride*jlevel + lstride*llevel;
    const float*    pJKData = dataF.data() + istride*ilevel + lstride*llevel;
    const double*  pIKLData = dataD.data() + jstride*jlevel;
    const float*  pIJKLData = dataF.data();

    serializer.WriteField(  "ik", sp,   pIKData, ibstrided, jbstrided, kbstrided, lbstrided);
    serializer.WriteField(  "jk", sp,   pJKData, ibstridef, jbstridef, kbstridef, lbstridef);
    serializer.WriteField( "ikl", sp,  pIKLData, ibstrided, jbstrided, kbstrided, lbstrided);
    serializer.WriteField("ijkl", sp, pIJKLData, ibstridef, jbstridef, kbstridef, lbstridef);

    // Check metainfo
    std::ifstream dbfs("Data.json");
    std::string dbtxt((std::istreambuf_iterator<char>(dbfs)),
                       std::istreambuf_iterator<char>());
    dbfs.close();
    JSONNode dbnode = libjson::parse(dbtxt);
    JSONNode fieldstable, offsettable, globalinfo;
    ASSERT_EQ(3, dbnode.size());
    ASSERT_NO_THROW(fieldstable = dbnode.at("FieldsTable"));
    ASSERT_NO_THROW(offsettable = dbnode.at("OffsetTable"));
    ASSERT_NO_THROW(globalinfo  = dbnode.at("GlobalMetainfo"));
    ASSERT_EQ(4, fieldstable.size());
    ASSERT_EQ(1, offsettable.size());
    ASSERT_LE(1, globalinfo.size());
    ASSERT_EQ(std::string("centralized"), globalinfo.at("__format").as_string());

    // Check savepoint metainfo
    Savepoint spload;
    ASSERT_EQ(std::string("MySavepoint"), offsettable[0]["__name"].as_string());
    ASSERT_EQ(0, offsettable[0]["__id"].as_int());
    ASSERT_EQ(3.125, offsettable[0]["Value"].as_float());
    ASSERT_EQ(3.625f, offsettable[0]["ValueF"].as_float());
    ASSERT_EQ(std::string("Andrea Arteaga"), offsettable[0]["MyName"].as_string());
    ASSERT_EQ(26, offsettable[0]["MyAge"].as_int());
    ASSERT_TRUE(offsettable[0]["ILikeThis"].as_bool());

    {   // Check IK

        // Read data
        std::ifstream fs("Data_ik.dat", std::ios::binary);
        fs.seekg(0, fs.end);
        int filelength = fs.tellg();
        fs.seekg(0, fs.beg);
        ASSERT_EQ(sizeof(double)*isize*ksize, filelength);

        std::vector<char> rawdata(filelength);
        fs.read(rawdata.data(), filelength);
        fs.close();

        // Check data
        const double* pNewData = reinterpret_cast<const double*>(rawdata.data());
        for (int i = 0; i < isize; ++i)
            for (int k = 0; k < ksize; ++k)
            {
                const int j = jlevel, l = llevel;
                const double value = *(pNewData + k*isize + i);
//.........这里部分代码省略.........
开发者ID:andyspiros,项目名称:serialbox,代码行数:101,代码来源:SerializerUnittest.cpp


注:本文中的JSONNode::at方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。