簡單的C++ JSON庫:SimpleJSON

碼頭工人 9年前發布 | 59K 次閱讀 JSON開發包 Simplejson

SimpleJSON是一個輕量級的JSON庫,用于在C++中從JSON格式導出數據。By taking advantage of templates and operator overloading on the backend, you're able to create and work with JSON objects right away, just as you would expect from a language such as JavaScript. SimpleJSON is packaged as a single C++ Header file "json.hpp".

Upcoming Features

SimpleJSON is still missing some features, which I hope to get done soon!

  • Import JSON from a string.
  • DONE Convert from a JSON object to primitive. Limited to String, Int, Float, and Bool.
  • DONE Allow users to assign to the next available any array index to append to the array:
  JSON array;
  array[0] = "Value";
  array[1] = 2;
  array[2] = true;
  array[4] = 1.1; // OK: Element 3 will be initialized to null.

One of the biggests goals for SimpleJSON is for it to be lightweight, and small. Having complicated logic isn't bad, but it bloats the codebase in most cases. I'd like to keep things small rather than put in big features that take a ton of space.

If you run into any bugs, please submit a bug!

Example

More examples can be found in the 'examples' directory. They're the closest thing to an API doc until I have time to write one.

#include "json.hpp"

int main() {
  json::JSON obj;
  // Create a new Array as a field of an Object.
  obj["array"] = json::Array( true, "Two", 3, 4.0 );
  // Create a new Object as a field of another Object.
  obj["obj"] = json::Object();
  // Assign to one of the inner object's fields
  obj["obj"]["inner"] = "Inside";

  // We don't need to specify the type of the JSON object:
  obj["new"]["some"]["deep"]["key"] = "Value";
  obj["array2"].append( false, "three" );

  std::cout << obj << std::endl;
}

Output:

{
  "array" : [true, "Two", 3, 4.000000],
  "array2" : [false, "three"],
  "new" : {
    "some" : {
      "deep" : {
        "key" : "Value"
      }
    }
  },
  "obj" : {
    "inner" : "Inside"
  }
}

This example can also be written another way:

#include "json.hpp"
#include <iostream>

using json::JSON;

int main() {
    JSON obj = {
        "array", json::Array( true, "Two", 3, 4.0 ),
        "obj", {
            "inner", "Inside"
        },
        "new", { 
            "some", { 
                "deep", { 
                    "key", "Value" 
                } 
            } 
        },
        "array2", json::Array( false, "three" )
    };

    std::cout << obj << std::endl;

項目主頁:http://www.baiduhome.net/lib/view/home/1424572684697

 本文由用戶 碼頭工人 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!