close

    在現今的資訊科技發展,到處可見Json資料的處理。

     今天凱吉介紹一款open source的c++類別庫rapid json。該類別庫提供高效,簡單易用的API讓開發人員迅速開發相關應用。

     以下為一段Json文件:

      {
    "Int": 1234, 
    "Double": 75.0000001, 
    "String": "Hello World", 
    "Object": {
        "name": "Max", 
        "age": 18
    }, 
    "IntArray": [
        1, 
        2, 
        3
    ], 
    "DoubleArray": [
        1.0, 
        2.0, 
        3.0
    ], 
    "StringArray": [
        "1", 
        "10", 
        "100"
    ], 
    "MixedArray": [
        "ggyy", 
        1234, 
        "ssss", 
        1.0021
    ], 
    "People": [
        {
            "name": "Larry", 
            "age": 38, 
            "sex": true
        }, 
        {
            "name": "Karcher", 
            "age": 38, 
            "sex": true
        }, 
        {
            "name": "Sam", 
            "age": 50, 
            "sex": true
        }
    ]
}

 

 

一、Write Json Format :

#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include <iostream>
#include <string>
 
using namespace std;
 
void Serialize_1()
{
    rapidjson::StringBuffer strBuf;
    rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);
 
    writer.StartObject();
 
    // 整數型別
    writer.Key("Int");
    writer.Int(1);
 
     // 浮點數型別
    writer.Key("Double");
    writer.Double(12.0000001);
 
       // 字串型別
    writer.Key("String");
    writer.String("This is a string");
 
     // 自訂義結構型別
    writer.Key("Object");
    writer.StartObject();
    writer.Key("name");
    writer.String("qq849635649");
    writer.Key("age");
    writer.Int(25);
    writer.EndObject();
 
    //  陣列型別 (Array type)
    //  整數陣列(int array)
    writer.Key("IntArray");
    writer.StartArray();
    //顺序写入即可
    writer.Int(10);
    writer.Int(20);
    writer.Int(30);
    writer.EndArray();
 
      //  浮點數陣列 (Double array)
    writer.Key("DoubleArray");
    writer.StartArray();
    for(int i = 1; i < 4; i++)
    {
        writer.Double(i * 1.0);
    }
    writer.EndArray();
 
     //  字串陣列 (string array)
    writer.Key("StringArray");
    writer.StartArray();
    writer.String("one");
    writer.String("two");
    writer.String("three");
    writer.EndArray();
 
      //  混和型陣列(an array with mixed data types)
    writer.Key("MixedArray");
    writer.StartArray();
    writer.String("one");
    writer.Int(50);
    writer.Bool(false);
    writer.Double(12.005);
    writer.EndArray();
 
    //  自訂義資料陣列(an array customize data)
    writer.Key("People");
    writer.StartArray();
    for(int i = 0; i < 3; i++)
    {
        writer.StartObject();
        writer.Key("name");
        writer.String("qq849635649");
        writer.Key("age");
        writer.Int(i * 10);
        writer.Key("sex");
        writer.Bool((i % 2) == 0);
        writer.EndObject();
    }
    writer.EndArray();
 
    writer.EndObject();
 
    string data = strBuf.GetString();
    cout << data << endl;
}

 

二、 讀取Json format:

 

#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
 
string data =
        "{\"Int\":1,"
        "\"Double\":12.0000001,"
        "\"String\":\"This is a string\","
        "\"Object\":{\"name\":\"qq849635649\",\"age\":25},"
        "\"IntArray\":[10,20,30],"
        "\"DoubleArray\":[1.0,2.0,3.0],"
        "\"StringArray\":[\"one\",\"two\",\"three\"],"
        "\"MixedArray\":[\"one\",50,false,12.005],"
        "\"People\":[{\"name\":\"qq849635649\",\"age\":0,\"sex\":true},"
        "{\"name\":\"qq849635649\",\"age\":10,\"sex\":false},"
        "{\"name\":\"qq849635649\",\"age\":20,\"sex\":true}]}";
 
void parse() {
    // 建立 rapidjson 物件
    rapidjson::Document doc;
    // 首先進行parsing,没有錯誤才能進行各個字段的parsing
    if(!doc.Parse(data.data()).HasParseError())
    {
        // parse 整數型別(int type)
        if(doc.HasMember("Int") && doc["Int"].IsInt())
        {
            cout << "Int = " << doc["Int"].GetInt() << endl;
        }


        // parse 浮點數型別(float type)
        if(doc.HasMember("Double") && doc["Double"].IsDouble())
        {
            cout << "Double = " << doc["Double"].GetDouble() << endl;
        }
        // parse 字串型別(string type)
        if(doc.HasMember("String") && doc["String"].IsString())
        {
            cout << "String = " << doc["String"].GetString() << endl;
        }
        //  parse 物件型別(object type)
        if(doc.HasMember("Object") && doc["Object"].IsObject())
        {
            const rapidjson::Value& object = doc["Object"];
            if(object.HasMember("name") && object["name"].IsString())
            {
                cout << "Object.name = " << object["name"].GetString() << endl;
            }
            if(object.HasMember("age") && object["age"].IsInt())
            {
                cout << "Object.age = " << object["age"].GetInt() << endl;
            }
        }
        /

      // 解析陣列(Array)類型

        //  整數陣列( int array)
        if(doc.HasMember("IntArray") && doc["IntArray"].IsArray())
        {
            // 将文字轉換為rapidjson::Value类型
            const rapidjson::Value& array = doc["IntArray"];
            // 取得陣列長度
            size_t len = array.Size();
            // 透過loop掃完所有元素,記得将元素轉換为int,即需要呼叫GetInt()
            for(size_t i = 0; i < len; i++)
            {
                cout << "IntArray[" << i << "] = " << array[i].GetInt() << endl;
            }
        }
        //  double 陣列( double array)
        if(doc.HasMember("DoubleArray") && doc["DoubleArray"].IsArray())
        {
            const rapidjson::Value& array = doc["DoubleArray"];
            size_t len = array.Size();
            for(size_t i = 0; i < len; i++)
            {
                //为防止类型不匹配,一般会添加类型校验
                if(array[i].IsDouble())
                {
                    cout << "DoubleArray[" << i << "] = " << array[i].GetDouble() << endl;
                }
            }
        }
        // 字串陣列(string array)
        if(doc.HasMember("StringArray") && doc["StringArray"].IsArray())
        {
            const rapidjson::Value& array = doc["StringArray"];
            size_t len = array.Size();
            for(size_t i = 0; i < len; i++)
            {
                if(array[i].IsString())
                {
                    cout << "StringArray[" << i << "] = " << array[i].GetString() << endl;
                }
            }
        }
        // array with mixed type
        if(doc.HasMember("MixedArray") && doc["MixedArray"].IsArray())
        {
            const rapidjson::Value& array = doc["MixedArray"];
            size_t len = array.Size();
            for(size_t i = 0; i < len; i++)
            {
                // 為防止型態不匹配,做型別檢查
                if(array[i].IsString())
                {
                    cout << "MixedArray[" << i << "] = " << array[i].GetString() << endl;
                }
                else if(array[i].IsBool())
                {
                    cout << "MixedArray[" << i << "] = " << array[i].GetBool() << endl;
                }
                else if(array[i].IsInt())
                {
                    cout << "MixedArray[" << i << "] = " << array[i].GetInt() << endl;
                }
                else if(array[i].IsDouble())
                {
                    cout << "MixedArray[" << i << "] = " << array[i].GetDouble() << endl;
                }
            }
        }
        //  結構數據陣列(Array with custom struct)
        if(doc.HasMember("People") && doc["People"].IsArray())
        {
            const rapidjson::Value& array = doc["People"];
            size_t len = array.Size();
            for(size_t i = 0; i < len; i++)
            {
                const rapidjson::Value& object = array[i];
                 // 為防止型態不匹配,做型別檢查
                if(object.IsObject())
                {
                    cout << "ObjectArray[" << i << "]: ";
                    if(object.HasMember("name") && object["name"].IsString())
                    {
                        cout << "name=" << object["name"].GetString();
                    }
                    if(object.HasMember("age") && object["age"].IsInt())
                    {
                        cout << ", age=" << object["age"].GetInt();
                    }
                    if(object.HasMember("sex") && object["sex"].IsBool())
                    {
                        cout << ", sex="  << (object["sex"].GetBool() ? "Men" : "Female") << endl;
                    }
                }
            }
        }
    }
    /**
     *    最后注意:因为rapidjson不會做安全檢查。 

     *  以int型別为例子
     * “if(object.HasMember("age") && object["age"].IsInt()) {}”
     */
}
 

arrow
arrow
    文章標籤
    c++ Json Dom
    全站熱搜

    凱吉 發表在 痞客邦 留言(0) 人氣()