RapidJson parsing (1), rapidjson Parsing

Source: Internet
Author: User

RapidJson parsing (1), rapidjson Parsing

RapidJson parsing (1)

DionysosLai (906391500@qq.com)

Json is a lightweight data exchange format that is easy to read and write, and easy to parse and generate by machines. Json is smaller, faster to read and write, and easier to parse than XML. On the other hand, as an upgraded version of json, Rapidjson has better efficiency advantages.

 

Json syntax rules

1. Data in name/value pairs

Json data writing format: Name/value pair.

The name/value pair includes the field name (in double quotation marks) followed by a colon, followed by the value:

For example:

"Subject": "English"

 

Json values can be numbers (integers or floating-point numbers), strings (in double quotes), logical values (true or false), arrays (in square brackets), object (in curly brackets), null.

Json objects can contain multiple name/value pairs:

For example:

{"Subject": "English", "subject": "Math "}

 

Json Arrays can contain objects:

For example:

{"Student ":[

{"Subject": "English", "subject": "Math "},

{"Subject": "Yuwen", "subject": "Music "},

]

}

2. Data is separated by commas (,).

Note that the last data should not contain commas,

3. curly braces are used to save objects.

4. square brackets are used to save arrays.


Rapdijson Parsing

Json itself is the JavaScript Object Notation (JavaScriptOjbect Notation), which is easy to parse at the javascript level. For c ++, you must import the relevant library files. Cocos2dx introduced the rapidjson library after version 2.1. Therefore, RapidJson Parsing is used here. The content mentioned later is also based on the cocos2dx engine (here the version is: cocos2d-x-3.2rc0)

Before json parsing, you must first understand several concepts related to json:

Value: value is actually var. For value, it can be understood as int, string, bool, and other data types. For defining Value value, it is just a definition and its data type has not yet been determined. If the value is clear, its data type is determined accordingly.

The Json data type is a map, expressed as the key-value form. There are several methods to convert Value to the basic data type:

Vall. SetArray () vall. SetArrayRaw () vall. SetBool () vall. SetDouble () vall. SetInt ()

Vall. SetNull () vall. SetObject () vall. SetString () vall. SetStringRaw () vall. SetUint ();

Vall. SetUint64 ()

At the same time, the value data type can be set repeatedly.


Write: encode the Value data into a json data format;

Reader: In contrast to Writer, data in json format is parsed into a Value.

Json: Readerreader;

1. Data Parsing

First, there is a json file to be parsed: "test. json". Note that the json file format is generally suffixed with "josn. At the same time, the json file encoding method is: UTF-8 without BOM format. The content of the "test. json" file is as follows:

{

"Hello": "world ",

"T": true,

"F": false,

"N": null,

"I": 123,

"Pi": 3.1416,

"":[

1,

2,

3,

4

]

}

It contains several common data formats: string, bool, null, int, etc.

 

Read and parse data into json format

Data Reading: whether it is a string, a file, or other form, it is expressed as a readable string. If it is in the file format, it is standard to read the file content.

Read File data:

        SSIZE_T size;unsigned char* ch = FileUtils::getInstance()->getFileData("test.json","r", &size);std::string data = std::string((const char* )ch, size);

Note that writing in this way is not allowed:

Std: string data = (const char *) CCFileUtils: sharedFileUtils ()-> getFileData ("DataTestQu. json "," r ", & size); // <reads a json File

This is because the format conversion error occurs.

The next step is to parse the data into json format:

Document doc; // <operations related to creating a Document Object rapidJson are all in the Document class doc. parse <0> (data. c_str (); // <Parse Json data through the Parse method if (doc. hasParseError () {CCLOG ("GetParseError % s \ n", doc. getParseError ());}

Note that the parsed document (JSON resolution exists in xml dom form) must be judged to determine whether the parsing is correct. Otherwise, all subsequent processing will be invalid.

Json Data Reading and modification-operation on values

For Data Reading and value change, the basic idea is to use value to read the key value and determine the key value type. Based on the key value type, the corresponding method is used to change the output and value. The related code is as follows:

Rapidjson: Value & valString = doc ["hello"]; // <reads the Value of the key "hello". According to our json document, if (valString. isString () // <determines whether it is a string {const char * ch = valString. getString (); log (ch); log (valString. getString (); valString. setString ("newString"); log (valString. getString ();} rapidjson: Value & valArray = doc ["a"]; // <read key "a" Value. According to our json document, is an array if (valArray. isArray () // <determines whether the val type is an array. The value corresponding to the Tollgate key is actually an array {for (int I = 0; I <valArray. capacity (); ++ I) {rapidjson: Value & first = valArray [I]; /// <obtain the I-th element in val. Based on the json file 'val ', there are four elements in 'val': CCLOG ("% f", first. getDouble (); // <convert the value to the Double type and print the result as 0.5 first. setDouble (10.f); CCLOG ("% f", first. getDouble (); // <convert the value to the Double type and print the result as 0.5 S }}


Json data operations-key operations

1. Add a member object

A member object must be in the key-value format. Therefore, you must specify the values of key and value. Add a member object. The principle is to allocate the space of the member variable under the dom data parsed in json at first, and then add the member object.

Add a String object, a null object, and an array object as follows:

/// Add a String object; rapidjson: Document: AllocatorType & allocator = doc. getAllocator (); // <The distribution of the obtained initial data: rapidjson: Value strObject (rapidjson: kStringType); // <add string method 1 strObject. setString ("love"); doc. addMember ("hello1", strObject, allocator);/* doc. addMember ("hello1", "love you", allocator); // <Add a string Method 2: add an object to the allocator * // Add a null object rapidjson:: Value nullObject (rapidjson: kNullType); doc. addMember ("nul L ", nullObject, allocator); // <add an object to the allocator // Add an array object rapidjson: Value array (rapidjson: kArrayType ); /// <create an array object rapidjson: Value object (rapidjson: kObjectType); /// <create an object in the array. Object. addMember ("id", 1, allocator); object. addMember ("name", "lai", allocator); object. addMember ("age", "12", allocator); object. addMember ("low", true, allocator); array. pushBack (object, allocator); doc. addMember ("player", array, allocator ); /// <Add the preceding array content to an array named "player" /// Add a member object rapidjson to the existing array :: value & category1 = doc ["a"]; category1.pushback (2.0, allocator );


2. Change the key name.

No

3. delete a member object

The member object deletion method has a unified method: RemoveMember. For an array object, if you want to delete the last element, you can use the popBack method ;. Example:

/// Delete the element rapidjson: Value & policray2 = doc ["a"]; // <reads the key "a" Value. According to our json document, is an array of javasray2.popback (); // <Delete the last member object of the array if (doc. removeMember ("I") // <Delete the member variable {log ("delet imember OK! ");}


Write Json data to a file

The preceding Write interface is called to encode the Value data into a json data format. You can Write the data to a file. Example:

/// Re-write json data into the file --- delete the file first, and then write the content rapidjson: StringBuffer; rapidjson: Writer <rapidjson: StringBuffer> writer (buffer ); doc. accept (writer); # if (CC_TARGET_PLATFORM = CC_PLATFORM_WIN32) system ("delE: \ cocos2d-x-3.2rc0 \ tests \ cpp-empty-test \ Resources \ test. josn "); // <delete the FILE first --- read data from the file before, so make sure that the FILE * file = fopen (" test. json "," wb "); if (file) {fputs (buffer. getString (), file); fclose (file );} # Else if (CC_TARGET_PLATFORM = CC_PLATFORM_ANDROID) // The principle is similar: first clear the file and write it. I will not write it here. # Endif


So far, the article "RapidJson parsing (1)" is over. It involves almost all basic json operations, such as data parsing, key-value changes, and data re-writing. The last question is "change key name". Currently, there is no good way to solve the problem. I don't know who has a good idea. @ me. Thank you very much! Some code-related addresses can be seen on my git: https://github.com/DionysosLai/Coco2d-xRes/tree/master/Function%20%E5%8A%9F%E8%83%BD%E5% AE %9E%E7%8E%B0/RapidJson


1) if the points A (-1/2, 0) and B () are known, the analytical expression of the line AB is

1) set to y = kx + B generation A B
K = 2; B = 1 y = 2x + 1
2) downward translation, that is, the line AB and y axis at (0, (B-3) → y = 2x + 1-3 → y = 2x-2
Translate to left, add to right, subtract → y = 2 (x + 1)-2 → y = 2x
3) The analytical expression of a straight line about a straight line x =-1 (You Want To Talk About Linear Symmetry ...)
Y = 2x the x axis is equal to A (0, 0) and the symmetric point of the x =-1 line (with the x axis at (-) is)
Y = 2x intersection x =-1 in B (-1,-2), which is obtained by using the linear equation obtained by a' and B (for method reference, refer)

1) known f (3x + 1) = 4x + 3, fx analytical expression

Let t = 3x + 1 launch x = (t-1)/3 in the formula
F (t) = 4*(t-1)/3 + 3 = (4 t + 5)/3
So f (x) = (4x + 5)/3

Related Article

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.