json c++ 库使用.md

  1. picojson https://github.com/kazuho/picojson
  2. rapidjson
  3. nlohmann:json https://github.com/nlohmann/json

picojson:

#define PICOJSON_USE_LOCALE 0
#include "picojson.h"

// content
picojson::object c;
c["en"] = picojson::value("Test Message");

// ids
picojson::array ids;
ids.push_back(picojson::value(USER_ID));
ids.push_back(picojson::value("4db7cb0f-daca-49d6-b3dd-a96774de9f72")); // Nexus 5
ids.push_back(picojson::value("33ad9d96-df00-42a2-b5ab-73417f777d42")); // iphone 4s
ids.push_back(picojson::value("5ea075c5-016d-4f55-891c-3b6c4b393e49")); // ios simulator

// data
picojson::object data;
data["foo"] = picojson::value("bar");

//
picojson::object obj;
obj["contents"] = picojson::value(c);
obj["include_player_ids"] = picojson::value(ids);
obj["data"] = picojson::value(data);

picojson::value v(obj);
CCLOG("picojson json=%s", v.serialize().c_str());

rapidjson

#include "json/rapidjson.h"
#include "json/document.h"
#include "json/stringbuffer.h"
#include "json/writer.h"

rapidjson::Value c(rapidjson::kObjectType);
c.AddMember("en", "Test Message", doc.GetAllocator());

rapidjson::Value ids(rapidjson::kArrayType);
std::vector tmpIds = {USER_ID, "4db7cb0f-daca-49d6-b3dd-a96774de9f72", "33ad9d96-df00-42a2-b5ab-73417f777d42", "5ea075c5-016d-4f55-891c-3b6c4b393e49"};
int size = tmpIds.size();
for (int i = 0; i < size; i++)
{
rapidjson::Value o(rapidjson::kStringType);
o.SetString(tmpIds.at(i).c_str(), tmpIds.at(i).length());
ids.PushBack(o, doc.GetAllocator());
}

rapidjson::Value data(rapidjson::kObjectType);
data.AddMember("foo", rapidjson::Value("bar"), doc.GetAllocator());

rapidjson::Value obj(rapidjson::kObjectType);
obj.AddMember("contents", c, doc.GetAllocator());
obj.AddMember("include_player_ids", ids, doc.GetAllocator());
obj.AddMember("data", data, doc.GetAllocator());

rapidjson::StringBuffer  buffer;
rapidjson::Writer writer(buffer);
obj.Accept(writer);
CCLOG("rapidjson=%s", buffer.GetString());

nlohmann

#include "json.hpp"
nlohmann::json data = {
  {"contents", { {"en", "Test Message"} } },
  {"data", { {"foo", "bar"} } },
  {"include_player_ids", {USER_ID, "4db7cb0f-daca-49d6-b3dd-a96774de9f72", "33ad9d96-df00-42a2-b5ab-73417f777d42", "5ea075c5-016d-4f55-891c-3b6c4b393e49"} }
};

总结:

  1. rapidjson 使用起来最麻烦,nlohmann 最简单,picojson 适中。
  2. picojson 和 rapidjson 能够在 iOS、Android 运行,而 nlohmann 在 Android 上需要特别的设置:Application.mk
APP_STL := c++_shared
NDK_TOOLCHAIN_VERSION := clang3.6
APP_CPPFLAGS += -frtti -fexceptions

这就有项目依赖了,不一定能够使用,不如一个预编译好的 cocos2d-x 库!

  1. picojson 和 nlhmann 只需要包含一个头文件,超级棒!

最终选择一个使用顺手,代码量不太多,性能还过得去的库:picojson !

你可能感兴趣的:(json c++ 库使用.md)