Jsoncpp Use Method Daquan

Source: Internet
Author: User

Jsoncpp Use Method Daquan

SOURCE http://blog.csdn.net/yc461515457/article/details/52749575

Json (JavaScript Object Notation) is a lightweight data interchange format. In short, JSON is organized in the same way as a dictionary in Python, a map in C + +, by Key-value, and key is any unique string, and value can be either bool,int,string or nested JSON. Refer to the official website for JSON format.
Jsoncpp is an open source C + + library for working with JSON text, and here's a quick introduction to the common use of jsoncpp for JSON files.

Jsoncpp Common Variable Introduction

In Jsoncpp, there are several commonly used variables that are particularly important, first of all.

Json::value

Json::value is used to represent any of the value abstract data types in JSON, specifically, the value in JSON can be a data type:

    • Signed integer signed integer [Range:value::minint-value::maxint]
    • unsigned integer unsigned integer (range:0-Value::maxuint)
    • Double-precision floating-point number double
    • Strings UTF-8 String
    • Boolean-Type Boolean
    • Null ' null '
    • An ordered list of value an ordered list of value
    • Collection of Name/value pairs (JavaScript object)

You can use the [] method to take a value.

//Examples:Json::Value null_value; // nullJson::Value arr_value(Json::arrayValue); // []Json::Value obj_value(Json::objectValue); // {}

Json::reader

Json::reader can parse the JSON source target to get a parsed json::value, usually the string or file input stream can be used as the source target.

Suppose you now have a Example.json file

{    "encoding" : "UTF-8",    "plug-ins" : [ "python", "c++", "ruby" ], "indent" : { "length" : 3, "use_space": true }}

To parse a JSON file using Json::reader:
bool parse (const std::string &document, Value &root, bool collectComments=true)bool parse (std::istream &is, Value &root, bool collectComments=true)

Json::Value root;Json::Reader reader;std::ifstream ifs("example.json");//open file example.jsonif(!reader.parse(ifs, root)){ // fail to parse}else{ // success std::cout<<root["encoding"].asString()<<endl; std::cout<<root["indent"]["length"].asInt()<<endl;}

Parsing a string using Json::reader
bool Json::Reader::parse ( const char * beginDoc,        const char * endDoc, Value & root, bool collectComments = true ) 

 Json::Value root; Json::Reader reader; const char* s = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}"; if(!reader.parse(s, root)){ // "parse fail"; } else{ std::cout << root["uploadid"].asString();//print "UP000000" }

Json::writer

Json::writer and Json::reader instead, the Json::value object is written to the string object, and Json::writer is an abstract class, Json::fastwriter and Json by two subclasses: Styledwriter inheritance.
In short, Fastwriter is a unformatted write, so JSON looks messy and unformatted, and Styledwriter is written with a format that looks more friendly.

Json::value Root;Json::reader Reader;Json::fastwriter Fwriter;Json::styledwriter Swriter; if (! Reader. Parse ("Example.json", root) {//parse fail return 0;} std::string str = fwriter (root);  Std::ofstream ofs ("Example_fast_writer.json"); ofs << str; OFS. Close (); str = Swriter ( root); ofsOpen ("Example_styled_writer.json"); ofs << str; OFS. Close ();  

Results:
Example_styled_writer.json

{    "encoding" : "UTF-8",    "plug-ins" : [ "python", "c++", "ruby" ], "indent" : { "length" : 3, "use_space": true }}

Example_fast_writer.json

{"encoding" : "UTF-8","plug-ins" : ["python","c++","ruby"],"indent" : { "length" : 3, "use_space": true}}

Jsoncpp Other operations

With the Json::value described earlier, Json::reader, Json::reader can implement the basic operation of the Json file, here are some other common operations.

Determine if key exists
BOOL Json::value::ismember (Const char * key) constReturn True if the object has a member named Key. Note ' key ' must be null-terminated. BOOL Json::value::ismember ( const std::string & key) cons Tbool Json::value::ismember ( const char* key, const char * end) Const 

Print "Encoding is a member"if (Root.ismember ("Encoding")) {STD::cout<< "encoding is a member" <<STD::ENDL;} else{std::cout<< "encoding is not a member" <<STD::ENDL; //print "encode is not a member" if (Root.ismember ( encode")) {std::cout<<" encode is a member "<<STD::ENDL;} else{std::cout<< "encode is not a member" <<STD::ENDL;}     

Determines whether value is null

The first thing to do is to add a Key-value pair to Example.json:

{    "encoding" : "UTF-8",    "plug-ins" : [ "python", "c++", "ruby" ], "indent" : { "length" : 3, "use_space": true }, "tab-length":[], "tab":null}

A member function that determines whether NULL is

bool Json::Value::isNull ( ) const

if(root["tab"].isNull()){    std::cout << "isNull" <<std::endl;//print isNull}

if (Root.ismember ("Tab-length")) {Trueif (root["Tab-length"].isnull ()) {STD::cout <<"IsNull" <<Std::endl; }Else std::cout << "not Null" <<Std::endl; //print ' Not Null ', there is a array of object ([]), through this array object is empty std::cout << "E Mpty: "<< root[" Tab-length "].empty () << Std::endl;  Print Empty:1 std::cout << "size:" << root["Tab-length"].size () << std:: Endl //print size:0}                 

It is also worth emphasizing that the map in Json::value and C + + has a common feature, that is, when you try to access a nonexistent key, it automatically generates a value pair that is key-value by default. Other words

 root["anything-not-exist"].isNull(); //false root.isMember("anything-not-exist"); //true

The summary is to determine whether it contains a key, use the IsMember member function, whether value is null using the IsNull member function, if value is empty, you can use the empty () and size () member functions.

Get all the keys
typedef std::vector<std::string> Json::Value::MembersValue::Members Json::Value::getMemberNames ( ) constReturn a list of the member names.If null, return an empty list.Precondition type() is objectValue or nullValue Postcondition if type() was nullValue, it remains nullValue 

You can see that json::value::members is actually a vector of string, all keys are obtained by Getmembernames.

Delete Member
Value Json::value::removemember (Constchar*Key) RemoveandReturn the named member.DoNothing if it does not exist. Returns the removed Value, or null. Precondition type () is objectValue or Nullvalue postcondition type () is unchanged Value json::value::removeme Mber ( const std::string & key) bool Json::value::removemember (std::string const &  Key, Value *removed) Remove the named Map member. Update ' removed ' iff removed. Parameters key may contain embedded nulls. Returns true iff removed (no exceptions)            

Reference

Http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html

Jsoncpp Use Method Daquan

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.