Fuck Json(1)jsoncppシーケンス化/逆シーケンス化文字列と整数

1570 ワード

1、シーケンス化
// json object to json string
void test_serialize() {
    Json::Value root;
    Json::FastWriter writer;
    Json::Value object1;
    Json::Value object2;

    object1["id"] = 1;
    object2["name"] = "hello";
    root.append(object1);
    root.append(object2);

    std::string jsonStr = writer.write(root);
    std::cout << jsonStr << std::endl;
}

2、逆シーケンス化
void test_deserialize() {
    // sample
    std::string test = "{\"id\":1,\"name\":\"hello\"}";
    Json::Reader reader;
    Json::Value value;

    // deserialize
    if (reader.parse(test, value)) {
        int id = value["id"].asInt();
        std::string name = value["name"].asString();
        std::cout << id << " " << name << std::endl;
    } else {
        std::cout << "parse error" << std::endl;
    }   
}

3、ファイルディレクトリ構造
Makefile
include
   - json
      - ...
src
   - lib_json
      - ...

4、Makefile
CC = g++ 
CFLAGS = -I./include -I./src/lib_json -I./include/json
LDFLAGS = -L/usr/local/lib

SRC = $(wildcard \
    ./src/*.cpp \
    ./src/lib_json/*.cpp)
OBJS = $(SRC:%.cpp=%.o)

test_json: $(OBJS)
    $(CC) $(LDFLAGS) $(LIBS) $(OBJS) -o $@

%.o : %.cpp
    $(CC) -c $(CFLAGS) $< -o $@

.PHONY:
clean:
    rm -f \
        test_json \
        $(OBJS)

5、安い運行
make
./test_json