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


C++ Document::MemberBegin方法代码示例

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


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

示例1: OnReadStats

LRESULT Cdispatcher_uiDlg::OnReadStats(WPARAM wparam, LPARAM lParam) {
	char *buf = (char*)wparam;
	Document d;
	if (d.Parse(buf).HasParseError()) {
		int unicodeLen = MultiByteToWideChar(CP_ACP, 0, buf, -1, 0, 0);
		wchar_t *wc = new wchar_t[unicodeLen+1];
		memset(wc, 0, (unicodeLen + 1)*sizeof(wchar_t));
		MultiByteToWideChar(CP_ACP, 0, buf, -1, wc, unicodeLen);
		m_static_msg.SetWindowText(wc);
		delete[]wc;
	}
	else {
		//read/stats
		uint64_t count_service = 0;
		uint64_t count_dispatch = 0;
		for (Value::ConstMemberIterator iter = d.MemberBegin(); iter != d.MemberEnd(); ++iter) {
			const char * app = iter->name.GetString();
			count_service += iter->value["service"].GetUint64();
			count_dispatch += iter->value["dispatch"].GetUint64();
		}

		wchar_t tmp[1024];
		swprintf_s(tmp, L"%lld", count_dispatch);
		m_dispatch_count.SetWindowTextW(tmp);
		swprintf_s(tmp, L"%lld", count_service);
		m_service_count.SetWindowTextW(tmp);
	}
	return 0;
}
开发者ID:freesense,项目名称:zabbix_dp,代码行数:29,代码来源:dispatcher_uiDlg.cpp

示例2: Merge

/**
 * Merge one set of options into this one.
 * All settings in the input take precedence over anything currently stored.
 * @param json_string The serialised JSON string to merge from.
 * @return true iff successfully merged.
 */
bool Options::Merge(const char *json_string) {
    if (json_string) {
        Document d;
        d.Parse<0>(json_string);
        if (!d.HasParseError() && d.IsObject()) {
            //Loop through each family
            for (Value::ConstMemberIterator it = d.MemberBegin();
                 it != d.MemberEnd(); it++)
            {
                //Do we have a family of options? (e.g. an object)
                if (it->value.IsObject()) {
                    SetFamily(it->name.GetString());
                    //Loop through each option
                    for (Value::ConstMemberIterator optit = it->value.MemberBegin();
                         optit != it->value.MemberEnd(); optit++)
                    {
                        const char *optkey = optit->name.GetString();
                        switch (optit->value.GetType()) {
                            case kFalseType: case kTrueType:
                                Set(optkey, optit->value.GetBool());
                            case kNumberType:
                                if (optit->value.IsInt()) {
                                    Set(optkey, optit->value.GetInt());
                                } else if (optit->value.IsNumber()) {
                                    Set(optkey, optit->value.GetDouble());
                                } else if (optit->value.IsBool()) {
                                    Set(optkey, optit->value.GetBool());
                                }
                            break;
                            case kStringType:
                                Set(optkey, optit->value.GetString());
                            break;
                            case kNullType: //Ignore
                            break;
                            default:
                                Log(LOG_WARNING, "Ignoring unknown option %s of type %d",
                                    optkey, optit->value.GetType());
                        }
                    }
                } else {
                    Log(LOG_WARNING, "Ignoring unknown family %s of type %d",
                        it->name.GetString(), it->value.GetType());
                }
            }
            return true;
        }
    }

    return false;
}
开发者ID:picopter,项目名称:picopterx,代码行数:56,代码来源:opts.cpp

示例3: configStream

std::map<std::string, std::string> ConfigParser::GetConfigMap()
{
    std::map<std::string, std::string> configMap;

    stringstream err;
    FILE* fp = fopen(configPath.c_str(), "rb");

    if(!fp){
        err << "Could not open file " << configPath << "!";
        errors.push_back(err.str());
        return configMap;
    }

    char readBuffer[CONFIGPARSER_BUF_SIZE] = {};
    FileReadStream configStream(fp, readBuffer, sizeof(readBuffer));

    Document d;
    d.ParseStream(configStream);

    if(!d.IsObject()){
        return configMap; 
    }


    for(Value::MemberIterator it = d.MemberBegin(); it != d.MemberEnd(); ++it){
        if ( !it->name.IsString() )
        {
            LOG_RELEASE("Warning: JSON key value is not a string.");
            continue;
        }
        if(strcmp(it->name.GetString(),"Port") == 0){
            configMap[it->name.GetString()] = "";
        }
        else if(strcmp(it->name.GetString(),"Roster") == 0){
            configMap[it->name.GetString()] = "";
        }
        else{
            // Ignore non-string
            if ( it->value.IsString() )
            {
                configMap[it->name.GetString()] = it->value.GetString();
            }
        }
    }
    fclose(fp);

    return configMap;
}
开发者ID:muzzley,项目名称:alljoyn-muzzley-gateway-connector,代码行数:48,代码来源:ConfigParser.cpp

示例4: parseSprite

Sprites parseSprite(const std::string& image, const std::string& json) {
    using namespace rapidjson;

    Sprites sprites;

    // Parse the sprite image.
    const util::Image raster(image);
    if (!raster) {
        Log::Warning(Event::Sprite, "Could not parse sprite image");
        return sprites;
    }

    Document doc;
    doc.Parse<0>(json.c_str());

    if (doc.HasParseError()) {
        Log::Warning(Event::Sprite, std::string{ "Failed to parse JSON: " } + doc.GetParseError() +
                                        " at offset " + std::to_string(doc.GetErrorOffset()));
        return sprites;
    } else if (!doc.IsObject()) {
        Log::Warning(Event::Sprite, "Sprite JSON root must be an object");
        return sprites;
    } else {
        for (Value::ConstMemberIterator itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr) {
            const std::string name = { itr->name.GetString(), itr->name.GetStringLength() };
            const Value& value = itr->value;

            if (value.IsObject()) {
                const uint16_t x = getUInt16(value, "x", 0);
                const uint16_t y = getUInt16(value, "y", 0);
                const uint16_t width = getUInt16(value, "width", 0);
                const uint16_t height = getUInt16(value, "height", 0);
                const double pixelRatio = getDouble(value, "pixelRatio", 1);
                const bool sdf = getBoolean(value, "sdf", false);

                auto sprite = createSpriteImage(raster, x, y, width, height, pixelRatio, sdf);
                if (sprite) {
                    sprites.emplace(name, sprite);
                }
            }
        }
    }

    return sprites;
}
开发者ID:donpark,项目名称:mapbox-gl-native,代码行数:45,代码来源:sprite_parser.cpp

示例5: main

int main(int, char*[]) {
	////////////////////////////////////////////////////////////////////////////
	// 1. Parse a JSON text string to a document.

	const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
	printf("Original JSON:\n %s\n", json);

	Document document;  // Default template parameter uses UTF8 and MemoryPoolAllocator.

#if 0
	// "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream().
	if (document.Parse(json).HasParseError())
		return 1;
#else
	// In-situ parsing, decode strings directly in the source string. Source must be string.
	char buffer[sizeof(json)];
	memcpy(buffer, json, sizeof(json));
	if (document.ParseInsitu(buffer).HasParseError())
		return 1;
#endif

	printf("\nParsing to document succeeded.\n");

	////////////////////////////////////////////////////////////////////////////
	// 2. Access values in document. 

	printf("\nAccess values in document:\n");
	assert(document.IsObject());    // Document is a JSON value represents the root of DOM. Root can be either an object or array.

	assert(document.HasMember("hello"));
	assert(document["hello"].IsString());
	printf("hello = %s\n", document["hello"].GetString());

	// Since version 0.2, you can use single lookup to check the existing of member and its value:
	Value::MemberIterator hello = document.FindMember("hello");
	assert(hello != document.MemberEnd());
	assert(hello->value.IsString());
	assert(strcmp("world", hello->value.GetString()) == 0);
	(void)hello;

	assert(document["t"].IsBool());     // JSON true/false are bool. Can also uses more specific function IsTrue().
	printf("t = %s\n", document["t"].GetBool() ? "true" : "false");

	assert(document["f"].IsBool());
	printf("f = %s\n", document["f"].GetBool() ? "true" : "false");

	printf("n = %s\n", document["n"].IsNull() ? "null" : "?");

	assert(document["i"].IsNumber());   // Number is a JSON type, but C++ needs more specific type.
	assert(document["i"].IsInt());      // In this case, IsUint()/IsInt64()/IsUInt64() also return true.
	printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"]

	assert(document["pi"].IsNumber());
	assert(document["pi"].IsDouble());
	printf("pi = %g\n", document["pi"].GetDouble());

	{
		const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster.
		assert(a.IsArray());
		for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t.
			printf("a[%d] = %d\n", i, a[i].GetInt());

		int y = a[0].GetInt();
		(void)y;

		// Iterating array with iterators
		printf("a = ");
		for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
			printf("%d ", itr->GetInt());
		printf("\n");
	}

	// Iterating object members
	static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };
	for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr)
		printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]);

	////////////////////////////////////////////////////////////////////////////
	// 3. Modify values in document.

	// Change i to a bigger number
	{
		uint64_t f20 = 1;   // compute factorial of 20
		for (uint64_t j = 1; j <= 20; j++)
			f20 *= j;
		document["i"] = f20;    // Alternate form: document["i"].SetUint64(f20)
		assert(!document["i"].IsInt()); // No longer can be cast as int or uint.
	}

	// Adding values to array.
	{
		Value& a = document["a"];   // This time we uses non-const reference.
		Document::AllocatorType& allocator = document.GetAllocator();
		for (int i = 5; i <= 10; i++)
			a.PushBack(i, allocator);   // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's.

		// Fluent API
		a.PushBack("Lua", allocator).PushBack("Mio", allocator);
	}

//.........这里部分代码省略.........
开发者ID:mlqcmlmc,项目名称:MyCode,代码行数:101,代码来源:TesrRapidJsonMain.cpp

示例6: parseBatchUpdate

/* ****************************************************************************
*
* parseBatchUpdate - 
*/
std::string parseBatchUpdate(ConnectionInfo* ciP, BatchUpdate* burP)
{
  Document document;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "JSON Parse Error");
    ec.fill(ERROR_STRING_PARSERROR, "Errors found in incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }

  if (!document.IsObject())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "JSON Parse Error");
    ec.fill("BadRequest", "JSON Parse Error");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (document.ObjectEmpty())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "Empty JSON payload");
    ec.fill("BadRequest", "empty payload");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (!document.HasMember("entities"))
  {
    ErrorCode    ec;
    std::string  details = "Invalid JSON payload, mandatory field /entities/ not found";

    alarmMgr.badInput(clientIp, details);
    ec.fill("BadRequest", details);
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (!document.HasMember("actionType"))
  {
    ErrorCode    ec;
    std::string  details = "Invalid JSON payload, mandatory field /actionType/ not found";

    alarmMgr.badInput(clientIp, details);
    ec.fill("BadRequest", details);
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }

  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    if (name == "entities")
    {
      std::string r = parseEntityVector(ciP, iter, &burP->entities, true); // param 4: attributes are allowed in payload

      if (r != "OK")
      {
        ErrorCode ec("BadRequest", r);

        alarmMgr.badInput(clientIp, r);
        ciP->httpStatusCode = SccBadRequest;
        return ec.toJson(true);
      }
    }
    else if (name == "actionType")
    {
      burP->updateActionType.set(iter->value.GetString());
    }
    else
    {
      std::string  description = std::string("Unrecognized field in JSON payload: /") + name + "/";
      ErrorCode    ec("BadRequest", description);

      alarmMgr.badInput(clientIp, description);
      ciP->httpStatusCode = SccBadRequest;

      return ec.toJson(true);
    }
  }

  return "OK";
}
开发者ID:Findeton,项目名称:fiware-orion,代码行数:100,代码来源:parseBatchUpdate.cpp

示例7: decode

GameState* JsonEncodeDecode::decode(const char *buffer)
{
	Document doc;

	// Parse and catch errors
	if (doc.Parse(buffer).HasParseError())
	{
		printf("\n----------\nError (offset %u): %s\n----------\n",
				(unsigned)doc.GetErrorOffset(),
				GetParseError_En(doc.GetParseError()));
		return NULL;
	}

	// Create new GameState
	GameState* state = new GameState();

	// Iterate through JSON document
	for (Value::ConstMemberIterator itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr)
	{
		/*
		 * GAME OVER STATE
		 */
		if (strcmp(itr->name.GetString(), "GameOver") == 0)
		{
			int gameOver = itr->value.GetInt();
			state->setGameOver(gameOver);
		}

		/*
		 * TIME TO RESTART
		 */
		if (strcmp(itr->name.GetString(), "SecToRestart") == 0)
		{
			int secToRestart = itr->value.GetInt();
			state->setSecToRestart(secToRestart);
		}

		/*
		 * VEHICLES
		 */
		if (strcmp(itr->name.GetString(), "Vehicles") == 0)
		{
			// If Vehicles is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Vehicles array is not array\n----------\n");
				return NULL;
			}

			const Value& vehicleArray = itr->value;
			for (SizeType i = 0; i < vehicleArray.Size(); i++)
			{
				if (decodeVehicle(state, vehicleArray[i]) == -1)
				{
					printf("\n----------\nError decoding vehicles\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * BULLETS
		 */
		if (strcmp(itr->name.GetString(), "Bullets") == 0)
		{
			// If Bullets is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Bullets array is not array\n----------\n");
				return NULL;
			}

			const Value& bulletArray = itr->value;
			for (SizeType i = 0; i < bulletArray.Size(); i++)
			{
				if (decodeBullet(state, bulletArray[i]) == -1)
				{
					printf("\n----------\nError decoding bullets\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * BASES
		 */
		if (strcmp(itr->name.GetString(), "Bases") == 0)
		{
			// If Bases is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Bases array is not array\n----------\n");
				return NULL;
			}

			const Value& basesArray = itr->value;
			for (SizeType i = 0; i < basesArray.Size(); i++)
			{
				if (decodeBase(state, basesArray[i]) == -1)
				{
//.........这里部分代码省略.........
开发者ID:awesomegroupidunno,项目名称:game-client,代码行数:101,代码来源:JsonEncodeDecode.cpp

示例8: if

/* ****************************************************************************
*
* parseContextAttributeCompoundValueStandAlone - 
*/
std::string parseContextAttributeCompoundValueStandAlone
(
  Document&            document,
  ContextAttribute*    caP,
  orion::ValueType     valueType
)
{
  caP->compoundValueP            = new orion::CompoundValueNode();
  caP->compoundValueP->name      = "TOP";
  caP->compoundValueP->container = caP->compoundValueP;
  caP->compoundValueP->valueType = caP->valueType;  // Convert to other type?
  caP->compoundValueP->path      = "/";
  caP->compoundValueP->rootP     = caP->compoundValueP;
  caP->compoundValueP->level     = 0;
  caP->compoundValueP->siblingNo = 0;

  orion::CompoundValueNode*   parent  = caP->compoundValueP;


  //
  // Children of the node
  //
  if (caP->valueType == orion::ValueTypeVector)
  {
    int counter  = 0;

    for (Value::ConstValueIterator iter = document.Begin(); iter != document.End(); ++iter)
    {
      std::string                nodeType  = jsonParseTypeNames[iter->GetType()];
      orion::CompoundValueNode*  cvnP      = new orion::CompoundValueNode();
      char                       itemNo[4];

      snprintf(itemNo, sizeof(itemNo), "%03d", counter);

      cvnP->valueType  = stringToCompoundType(nodeType);
      cvnP->container  = parent;
      cvnP->rootP      = parent->rootP;
      cvnP->level      = parent->level + 1;
      cvnP->siblingNo  = counter;
      cvnP->path       = parent->path + "[" + itemNo + "]";


      if (nodeType == "String")
      {
        cvnP->stringValue = iter->GetString();
      }
      else if (nodeType == "Number")
      {
        cvnP->numberValue = iter->GetDouble();
      }
      else if ((nodeType == "True") || (nodeType == "False"))
      {
        cvnP->boolValue   = (nodeType == "True")? true : false;
      }
      else if (nodeType == "Null")
      {
        cvnP->valueType = orion::ValueTypeNone;
      }
      else if (nodeType == "Object")
      {
        cvnP->path += "/";
        cvnP->valueType = orion::ValueTypeObject;
      }
      else if (nodeType == "Array")
      {
        cvnP->path += "/";
        cvnP->valueType = orion::ValueTypeVector;
      }

      parent->childV.push_back(cvnP);

      //
      // Start recursive calls if Object or Array
      //
      if ((nodeType == "Object") || (nodeType == "Array"))
      {
        parseContextAttributeCompoundValue(iter, caP, cvnP);
      }
      else if (!caP->typeGiven)
      {
        caP->type = defaultType(caP->valueType);
      }

      ++counter;
    }
  }
  else if (caP->valueType == orion::ValueTypeObject)
  {
    int counter  = 0;

    for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
    {
      std::string                nodeType = jsonParseTypeNames[iter->value.GetType()];
      orion::CompoundValueNode*  cvnP     = new orion::CompoundValueNode();

      cvnP->name       = iter->name.GetString();
//.........这里部分代码省略.........
开发者ID:Fiware,项目名称:context.Orion,代码行数:101,代码来源:parseContextAttributeCompoundValue.cpp

示例9: parseAttributeValue

/* ****************************************************************************
*
* parseAttributeValue - 
*/
std::string parseAttributeValue(ConnectionInfo* ciP, ContextAttribute* caP)
{
  Document   document;
  OrionError oe;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    LM_W(("Bad Input (JSON parse error)"));
    oe.fill(SccBadRequest, "Errors found in incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;;
    return oe.render(ciP, "");
  }


  if (!document.IsObject())
  {
    LM_E(("Bad Input (JSON Parse Error)"));
    oe.fill(SccBadRequest, "Error parsing incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;;
    return oe.render(ciP, "");
  }


  if (!document.HasMember("value"))
  {
    LM_W(("Bad Input (No attribute value specified"));
    oe.fill(SccBadRequest, "no attribute value specified");
    ciP->httpStatusCode = SccBadRequest;;
    return oe.render(ciP, "");
  }


  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    if (name != "value")
    {
      LM_W(("Bad Input (unexpected JSON field - accepting only 'value'"));
      oe.fill(SccBadRequest, "unexpected JSON field - accepting only /value/");
      ciP->httpStatusCode = SccBadRequest;;
      return oe.render(ciP, "");
    }


    if (type == "String")
    {
      caP->valueType   = orion::ValueTypeString;
      caP->stringValue = iter->value.GetString();
    }
    else if (type == "Number")
    {
      caP->numberValue  = iter->value.GetDouble();
      caP->valueType    = orion::ValueTypeNumber;
    }
    else if (type == "True")
    {
      caP->boolValue    = true;
      caP->valueType    = orion::ValueTypeBoolean;
    }
    else if (type == "False")
    {
      caP->boolValue    = false;
      caP->valueType    = orion::ValueTypeBoolean;
    }
    else if (type == "Array")
    {
      caP->valueType    = orion::ValueTypeVector;

      std::string r = parseContextAttributeCompoundValue(iter, caP, NULL);
      if (r != "OK")
      {
        LM_W(("Bad Input (json error in ContextAttributeObject::Vector"));
        return "json error in ContextAttributeObject::Vector";
      }
    }
    else if (type == "Object")
    {
      caP->valueType    = orion::ValueTypeObject;

      std::string r = parseContextAttributeCompoundValue(iter, caP, NULL);
      if (r != "OK")
      {
        LM_W(("Bad Input (json error in ContextAttributeObject::Object"));
        return "json error in ContextAttributeObject::Object";
      }
    }
  }

  return "OK";
}
开发者ID:fiwareulpgcmirror,项目名称:fiware-orion,代码行数:98,代码来源:parseAttributeValue.cpp

示例10: parseEntity

/* ****************************************************************************
*
* parseEntity - 
*
* This function is used to parse two slightly different payloads:
* - POST /v2/entities
* - POST /v2/entities/<eid>
*
* In the latter case, "id" CANNOT be in the payload, while in the former case, 
* "id" MUST be in the payload.
*
* In the case of /v2/entities/<eid>, the entityId of 'Entity* eP' is set in
* the service routine postEntity.
* 
*/
std::string parseEntity(ConnectionInfo* ciP, Entity* eP, bool eidInURL)
{
  Document document;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    LM_W(("Bad Input (JSON parse error)"));
    eP->errorCode.fill("ParseError", "Errors found in incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;;
    return eP->render(ciP, EntitiesRequest);
  }


  if (!document.IsObject())
  {
    LM_E(("Bad Input (JSON Parse Error)"));
    eP->errorCode.fill("ParseError", "Error parsing incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;;
    return eP->render(ciP, EntitiesRequest);
  }


  if (eidInURL == false)
  {
    if (!document.HasMember("id"))
    {
      LM_W(("Bad Input (No entity id specified"));
      eP->errorCode.fill("ParseError", "no entity id specified");
      ciP->httpStatusCode = SccBadRequest;;
      return eP->render(ciP, EntitiesRequest);
    }
  }


  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    if (name == "id")
    {
      if (eidInURL == false)
      {
        if (type != "String")
        {
          LM_W(("Bad Input (invalid JSON type for entity id"));
          eP->errorCode.fill("ParseError", "invalid JSON type for entity id");
          ciP->httpStatusCode = SccBadRequest;;
          return eP->render(ciP, EntitiesRequest);
        }

        eP->id = iter->value.GetString();
      }
      else  // "id" present in payload for /v2/entities/<eid> - not a valid payload
      {
        LM_W(("Bad Input ('id' is not a valid attribute"));
        eP->errorCode.fill("ParseError", "invalid input, 'id' as attribute");
        ciP->httpStatusCode = SccBadRequest;;
        return eP->render(ciP, EntitiesRequest);
      }
    }
    else if (name == "type")
    {
      if (type != "String")
      {
        LM_W(("Bad Input (invalid JSON type for entity type"));
        eP->errorCode.fill("ParseError", "invalid JSON type for entity type");
        ciP->httpStatusCode = SccBadRequest;;
        return eP->render(ciP, EntitiesRequest);
      }

      eP->type = iter->value.GetString();
    }
    else
    {
      ContextAttribute* caP = new ContextAttribute();
      eP->attributeVector.push_back(caP);

      std::string r = parseContextAttribute(ciP, iter, caP);
      if (r != "OK")
      {
        LM_W(("Bad Input (parse error in context attribute)"));
        eP->errorCode.fill("ParseError", r);
//.........这里部分代码省略.........
开发者ID:JJ,项目名称:fiware-orion,代码行数:101,代码来源:parseEntity.cpp

示例11: convertMultiple

void convertMultiple(const char* nameJSON, const char* nameCSV)	{
	//Prepare Input
	struct stat statbuf;
	stat(nameJSON, &statbuf);
	size_t fsize = statbuf.st_size;

	int fd = open(nameJSON, O_RDONLY);
	if (fd == -1) {
		throw runtime_error(string("json.open"));
	}

	const char *bufJSON = (const char*) mmap(NULL, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
	if (bufJSON == MAP_FAILED) {
		throw runtime_error(string("json.mmap"));
	}

	//Prepare output
	ofstream outFile;
	outFile.open(nameCSV);

	//Input loop
	size_t obj_start = 0;
	size_t obj_end = 0;
	char *line_bufJSON = NULL;
	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	stringstream ss;


	int flushCount = 0;
	while (obj_start < fsize) {
		size_t i = obj_start;
		for (; bufJSON[i] != '\n'; i++) {}
		obj_end = i;
		line_bufJSON = new char[obj_end - obj_start + 1];
		line_bufJSON[obj_end - obj_start] = '\0';
		memcpy(line_bufJSON, bufJSON + obj_start, obj_end - obj_start);

		//Triggering parser
		Document d;
		d.Parse(line_bufJSON);

		Value::ConstMemberIterator itrDoc = d.MemberBegin();
		Value::ConstMemberIterator itrDocEnd = d.MemberEnd();
		buffer.Clear();
		writer.Reset(buffer);

		//1st iteration unrolled to avoid unnecessary "if(first)" checks
		if (itrDoc != itrDocEnd) {
			if (itrDoc->value.IsObject()) {
				Value::ConstMemberIterator itr_ = itrDoc->value.MemberBegin();
				Value::ConstMemberIterator itrEnd_ = itrDoc->value.MemberEnd();
				iterateObject(itr_, itrEnd_, &buffer, &writer, ss);
			} else if (itrDoc->value.IsArray()) {
				Value::ConstValueIterator itr_ = itrDoc->value.Begin();
				Value::ConstValueIterator itrEnd_ = itrDoc->value.End();
				iterateArray(itr_, itrEnd_, &buffer, &writer, ss);
			} else if (itrDoc->value.IsBool()) {
				ss << itrDoc->value.GetBool();
			} else if (itrDoc->value.IsInt()) {
				ss << itrDoc->value.GetInt();
			} else if (itrDoc->value.IsInt64()) {
				ss << itrDoc->value.GetInt64();
			} else if (itrDoc->value.IsDouble()) {
				ss << itrDoc->value.GetDouble();
			} else if (itrDoc->value.IsString()) {
				ss << "\"" << itrDoc->value.GetString() << "\"";
			} else {
				throw runtime_error(string("Case missing from tokenizer"));
			}
		}
		itrDoc++;
		iterateObject(itrDoc, itrDocEnd, &buffer, &writer, ss);
		ss << "\n";

		//flushing to output file every 1000 entries
		flushCount++;
		if(flushCount % 1000 == 0)	{
			outFile << ss.rdbuf();
			ss.clear();
		}

		//Prepare next loop + cleanup
		delete line_bufJSON;
		obj_start = ++i;

	}

	outFile << ss.rdbuf();
	outFile.close();

	close(fd);
	munmap((void*) bufJSON,fsize);
}
开发者ID:manosk,项目名称:jsonToCSV,代码行数:94,代码来源:convertJSON.cpp

示例12: convert

void convert(const char* nameJSON, const char* nameCSV)	{
	
	//Prepare Input
	struct stat statbuf;
	stat(nameJSON, &statbuf);
	size_t fsize = statbuf.st_size;

	int fd = open(nameJSON, O_RDONLY);
	if (fd == -1) {
		throw runtime_error(string("json.open"));
	}

	const char *bufJSON = (const char*) mmap(NULL, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
	if (bufJSON == MAP_FAILED) {
		throw runtime_error(string("json.mmap"));
	}
	//Prepare output
	ofstream outFile;
	outFile.open(nameCSV);

	Document d;
	d.Parse(bufJSON);

	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	stringstream ss;
	Value::ConstMemberIterator itrDoc = d.MemberBegin();
	Value::ConstMemberIterator itrDocEnd = d.MemberEnd();

	if (itrDoc != itrDocEnd) {
		if (itrDoc->value.IsObject()) {
			Value::ConstMemberIterator itr_ = itrDoc->value.MemberBegin();
			Value::ConstMemberIterator itrEnd_ = itrDoc->value.MemberEnd();
			iterateObject(itr_, itrEnd_, &buffer, &writer, ss);
		} else if (itrDoc->value.IsArray()) {
			Value::ConstValueIterator itr_ = itrDoc->value.Begin();
			Value::ConstValueIterator itrEnd_ = itrDoc->value.End();
			iterateArray(itr_, itrEnd_, &buffer, &writer, ss);
		} else if (itrDoc->value.IsBool()) {
			ss << itrDoc->value.GetBool();
		} else if (itrDoc->value.IsInt()) {
			ss << itrDoc->value.GetInt();
		} else if (itrDoc->value.IsInt64()) {
			ss << itrDoc->value.GetInt64();
		} else if (itrDoc->value.IsDouble()) {
			ss << itrDoc->value.GetDouble();
		} else if (itrDoc->value.IsString()) {
			ss << "\"" << itrDoc->value.GetString() << "\"";
		} else {
			throw runtime_error(string("Case missing from tokenizer"));
		}
	}
	itrDoc++;
	iterateObject(itrDoc, itrDocEnd, &buffer, &writer, ss);

	outFile << ss.rdbuf();
	outFile.close();

	close(fd);
	munmap((void*) bufJSON,fsize);
}
开发者ID:manosk,项目名称:jsonToCSV,代码行数:61,代码来源:convertJSON.cpp

示例13: parseEntity

/* ****************************************************************************
*
* parseEntity - 
*
* This function is used to parse two slightly different payloads:
* - POST /v2/entities
* - POST /v2/entities/<eid>
*
* In the latter case, "id" CANNOT be in the payload, while in the former case, 
* "id" MUST be in the payload.
*
* In the case of /v2/entities/<eid>, the entityId of 'Entity* eP' is set in
* the service routine postEntity.
*
* Also, if the URI param 'options' includes the value 'keyValues', then the
* parse changes for compound values of attributes. If the value is a JSON object
* then there is no looking inside to find the 'value' field, but the attribute is
* always treated as a compound attribute.
* 
*/
std::string parseEntity(ConnectionInfo* ciP, Entity* eP, bool eidInURL)
{
  Document document;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    alarmMgr.badInput(clientIp, "JSON parse error");
    eP->oe.fill(SccBadRequest, "Errors found in incoming JSON buffer", ERROR_STRING_PARSERROR);
    ciP->httpStatusCode = SccBadRequest;
    return eP->render(ciP, EntitiesRequest);
  }


  if (!document.IsObject())
  {
    alarmMgr.badInput(clientIp, "JSON Parse Error");
    eP->oe.fill(SccBadRequest, "Errors found in incoming JSON buffer", ERROR_STRING_PARSERROR);
    ciP->httpStatusCode = SccBadRequest;
    return eP->render(ciP, EntitiesRequest);
  }


  if (eidInURL == false)
  {
    if (!document.HasMember("id"))
    {
      alarmMgr.badInput(clientIp, "No entity id specified");
      eP->oe.fill(SccBadRequest, "no entity id specified", "BadRequest");
      ciP->httpStatusCode = SccBadRequest;;

      return eP->render(ciP, EntitiesRequest);
    }
  }


  if (eidInURL == true)
  {
    if (document.HasMember("id"))
    {
      alarmMgr.badInput(clientIp, "entity id specified in payload");
      eP->oe.fill(SccBadRequest, "entity id specified in payload", "BadRequest");
      ciP->httpStatusCode = SccBadRequest;;

      return eP->render(ciP, EntitiesRequest);
    }

    if (document.HasMember("type"))
    {
      alarmMgr.badInput(clientIp, "entity type specified in payload");
      eP->oe.fill(SccBadRequest, "entity type specified in payload", "BadRequest");
      ciP->httpStatusCode = SccBadRequest;;

      return eP->render(ciP, EntitiesRequest);
    }
  }
  else if (document.ObjectEmpty()) 
  {
    //
    // Initially we used the method "Empty". As the broker crashed inside that method, some
    // research was made and "ObjectEmpty" was found. As the broker stopped crashing and complaints
    // about crashes with small docs and "Empty()" were found on the internet, we opted to use ObjectEmpty
    //
    alarmMgr.badInput(clientIp, "Empty payload");
    eP->oe.fill(SccBadRequest, "empty payload", "BadRequest");
    ciP->httpStatusCode = SccBadRequest;

    return eP->render(ciP, EntitiesRequest);
  }

  int membersFound = 0;
  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    ++membersFound;

    if (name == "id")
//.........这里部分代码省略.........
开发者ID:Fiware,项目名称:context.Orion,代码行数:101,代码来源:parseEntity.cpp

示例14: parseBatchQuery

/* ****************************************************************************
*
* parseBatchQuery - 
*/
std::string parseBatchQuery(ConnectionInfo* ciP, BatchQuery* bqrP)
{
  Document document;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "JSON Parse Error");
    ec.fill(ERROR_STRING_PARSERROR, "Errors found in incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }

  if (!document.IsObject())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "JSON Parse Error");
    ec.fill("BadRequest", "JSON Parse Error");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (document.ObjectEmpty())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "Empty JSON payload");
    ec.fill("BadRequest", "empty payload");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (!document.HasMember("entities") && !document.HasMember("attributes") && !document.HasMember("scopes"))
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "Invalid JSON payload, no relevant fields found");
    ec.fill("BadRequest", "Invalid JSON payload, no relevant fields found");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }

  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    if (name == "entities")
    {
      std::string r = parseEntityVector(ciP, iter, &bqrP->entities, false);  // param 4: attributes are NOT allowed in payload

      if (r != "OK")
      {
        ErrorCode ec("BadRequest", r);

        alarmMgr.badInput(clientIp, r);
        ciP->httpStatusCode = SccBadRequest;
        return ec.toJson(true);
      }
    }
    else if (name == "attributes")
    {
      std::string r = parseAttributeList(ciP, iter, &bqrP->attributeV);

      if (r != "OK")
      {
        ErrorCode ec("BadRequest", r);

        alarmMgr.badInput(clientIp, r);
        ciP->httpStatusCode = SccBadRequest;
        return ec.toJson(true);
      }
    }
    else if (name == "scopes")
    {
      std::string r = parseScopeVector(ciP, iter, &bqrP->scopeV);

      if (r != "OK")
      {
        ErrorCode ec("BadRequest", r);

        alarmMgr.badInput(clientIp, r);
        ciP->httpStatusCode = SccBadRequest;
        return ec.toJson(true);
      }
    }
    else
    {
      std::string  description = std::string("Unrecognizedfield in JSON payload: /") + name + "/";
      ErrorCode    ec("BadRequest", description);
//.........这里部分代码省略.........
开发者ID:Findeton,项目名称:fiware-orion,代码行数:101,代码来源:parseBatchQuery.cpp


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