Cocos2d-x Learning (5): cocos2d-x parsing json (using libjson Library)

Source: Internet
Author: User

Cocos2d-x is good, scalability is good, but its third-party library is not very mature, as Wang Zhe said, we need to find, such as json parsing and formatting.

 


Json is required for our network. json is used for many network parts. After all, it is lightweight... In the morning I saw someone mentioned two third-party libraries about json in the cocos2d-x Forum. One is jsoncpp and the other is libjson. In the morning I prefer jsoncpp and check its compilation process, it is quite complicated. I developed the scons (compiler) and compiled it. However, the link error will be reported on the iphone. I don't know how to solve it. I used it in the Mac app, normal... It turns out that the Mac is 64-bit, while the iphone needs 32-bit libraries and various answers, finally, I found a solution on the wiki on the official website ------- how to compile a 32-bit library on Mac 64-bit. After trying, I found that the compilation failed, as if it was the reason for the gcc version, let's look at the following warning, which is not very good for Mac support! Well, I admit that it is not the best choice across iphone and android. (It's easy to compile on ubuntu. If it's okay, it should be okay on android.) So in the afternoon, I switched to libjson.

 


1. Introduction to json
JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript (Standard ECMA-262 3rd Edition-December 1999. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, and so on ). These features make JSON an ideal data exchange language. Easy for reading and writing, and easy for machine parsing and generation.


JSON construction has two structures:

1. A collection of name/value pairs ). In different languages, it is understood as an object, record, struct, dictionary, and hash table ), keyed list or associative array ). 2. An ordered list of values ). In most languages, it is understood as an array ).


(Ps: These two sections are copied from Baidu encyclopedia, but the 2nd json structures are very important and are often ignored)

 


2. Compile
Some people in the Forum also asked how to use libjson. Wang Zhe's answer is to copy the source code directly to the project, so there must be no complicated compilation parameters, environment or other obstacles, so I copied it and compiled it. That's right! Engineering

(Copy the Source, Dependencies directory and JSONOptions. h, libjson. h under libjson)

 


(PS: just place the cursor on JSONOptions. h because it is evil. There are several macros and Their switch usage, and there is a bug in the source code ...)

 


3. Usage
Libjson provides us with two sets of interfaces: a set of c and a set of c ++, under the Getting Started directory of its directory. As for the choice, it is a matter of preference!

 


(1) Simple Syntax:

[Cpp]
<Span style = "font-size: 16px;"> JSONNODE * n = json_new (JSON_NODE );
Json_push_back (n, json_new_ I ("number", 88 ));
Json_push_back (n, json_new_a ("string", "oneRain "));
Json_push_back (n, json_new_a ("charactor", "Chinese "));

Json_char * jc = json_write_formatted (n );
CCLOG ("json: % s", jc );
Json_free (jc );
Json_delete (n); </span>
<Span style = "font-size: 16px;"> JSONNODE * n = json_new (JSON_NODE );
Json_push_back (n, json_new_ I ("number", 88 ));
Json_push_back (n, json_new_a ("string", "oneRain "));
Json_push_back (n, json_new_a ("charactor", "Chinese "));

Json_char * jc = json_write_formatted (n );
CCLOG ("json: % s", jc );
Json_free (jc );
Json_delete (n); </span> output result:

 


(2) simple reading:
Reading requires a simple parsing process. Of course, it does not have any. If there is no key


[Cpp]
<Span style = "font-size: 16px;"> void ParseJSON (JSONNODE * n)
{
If (n = NULL ){
Printf ("Invalid JSON Node1 \ n ");
Return;
}

JSONNODE_ITERATOR I = json_begin (n );
While (I! = Json_end (n )){
If (* I = NULL ){
Printf ("Invalid JSON Node2 \ n ");
Return;
}

// Recursively call ourselves to dig deeper into the tree
If (json_type (* I) = JSON_ARRAY | json_type (* I) = JSON_NODE ){
ParseJSON (* I );
}

// Get the node name and value as a string
Json_char * node_name = json_name (* I );

// Find out where to store the values
If (strcmp (node_name, "number") = 0 ){
Json_int_t node_value = json_as_int (* I );
CCLOG ("% d", node_value );
}
Else if (strcmp (node_name, "string") = 0 ){
Json_char * node_value = json_as_string (* I );
CCLOG ("% s", node_value );
Json_free (node_value );
}
Else if (strcmp (node_name, "charactor") = 0)
CCLOG ("% s", json_as_string (* I ));

// Cleanup and increment the iterator
Json_free (node_name );
++ I;
}
} </Span>
<Span style = "font-size: 16px;"> void ParseJSON (JSONNODE * n)
{
If (n = NULL ){
Printf ("Invalid JSON Node1 \ n ");
Return;
}

JSONNODE_ITERATOR I = json_begin (n );
While (I! = Json_end (n )){
If (* I = NULL ){
Printf ("Invalid JSON Node2 \ n ");
Return;
}

// Recursively call ourselves to dig deeper into the tree
If (json_type (* I) = JSON_ARRAY | json_type (* I) = JSON_NODE ){
ParseJSON (* I );
}

// Get the node name and value as a string
Json_char * node_name = json_name (* I );

// Find out where to store the values
If (strcmp (node_name, "number") = 0 ){
Json_int_t node_value = json_as_int (* I );
CCLOG ("% d", node_value );
}
Else if (strcmp (node_name, "string") = 0 ){
Json_char * node_value = json_as_string (* I );
CCLOG ("% s", node_value );
Json_free (node_value );
}
Else if (strcmp (node_name, "charactor") = 0)
CCLOG ("% s", json_as_string (* I ));

// Cleanup and increment the iterator
Json_free (node_name );
++ I;
}
} </Span> call Process


[Cpp]
<Span style = "font-size: 16px;"> char * json = "{\" number \ ": 88, \" string \ ": \" oneRain \", \ "charactor \": \ "Chinese Character \"}";
JSONNODE * nr = json_parse (json );
ParseJSON (nr );
Json_delete (nr); </span>
<Span style = "font-size: 16px;"> char * json = "{\" number \ ": 88, \" string \ ": \" oneRain \", \ "charactor \": \ "Chinese Character \"}";
JSONNODE * nr = json_parse (json );
ParseJSON (nr );
Json_delete (nr); </span> result

 


(3) json Array

In many cases, we need to store arrays in json format, which may be an array of objects or an array of basic variables. If it is an array of objects, you need to add some object applications and linked list operations to the ParseJSON method in the simple reading method to complete the desired data structure!

Of course, another common usage is: an array with only "value" and no "key", such as ["value1", "value2", "value3"], this format is often used to communicate with the server in the socket link. The following describes two methods for parsing and formatting respectively:

A. Parsing
Of course, a parsing function is still needed for output and recursion.


[Cpp]
<Span style = "font-size: 16px;"> void parseArrJSON (JSONNODE * n)
{
If (n = NULL)
{
CCLOG ("Invalid JSON Node \ n ");
Return;
}

// Parser
JSONNODE_ITERATOR it = json_begin (n );
While (it! = Json_end (n )){
If (* it = NULL ){
CCLOG ("Invalid JSON Node \ n ");
Return;
}

If (json_type (* it) = JSON_ARRAY | json_type (* it) = JSON_NODE ){
ParseArrJSON (* it );
}
Else {
// If the value does not have a key, you only need to obtain it.
Json_char * value = json_as_string (* it );
CCLOG ("% s", value );
Json_free (value );
}

++ It;
}

}
</Span>
<Span style = "font-size: 16px;"> void parseArrJSON (JSONNODE * n)
{
If (n = NULL)
{
CCLOG ("Invalid JSON Node \ n ");
Return;
}

// Parser
JSONNODE_ITERATOR it = json_begin (n );
While (it! = Json_end (n )){
If (* it = NULL ){
CCLOG ("Invalid JSON Node \ n ");
Return;
}

If (json_type (* it) = JSON_ARRAY | json_type (* it) = JSON_NODE ){
ParseArrJSON (* it );
}
Else {
// If the value does not have a key, you only need to obtain it.
Json_char * value = json_as_string (* it );
CCLOG ("% s", value );
Json_free (value );
}

++ It;
}

}
</Span> easy to use


[Cpp]
<Span style = "font-size: 16px;"> char * arrJson = "[\" value1 \ ", \" value2 \ ", \" value3 \ "]";
JSONNODE * an = json_parse (arrJson );
ParseArrJSON ();
Json_delete (an); </span>
<Span style = "font-size: 16px;"> char * arrJson = "[\" value1 \ ", \" value2 \ ", \" value3 \ "]";
JSONNODE * an = json_parse (arrJson );
ParseArrJSON ();
Json_delete (an); </span>


B. Format

That is, splicing a json string.


[Cpp]
<Span style = "font-size: 16px;"> JSONNODE * arrn = json_new (JSON_ARRAY );
Json_set_name (n, NULL );
Json_push_back (n, json_new_a (NULL, "one "));
Json_push_back (n, json_new_a (NULL, "Chinese character "));
Json_push_back (n, json_new_ I (NULL, 999999 ));

Json_char * arrjc = json_write (arrn );

CCLOG ("Json: % s, % d", arrjc, strlen (jc); </span>
<Span style = "font-size: 16px;"> JSONNODE * arrn = json_new (JSON_ARRAY );
Json_set_name (n, NULL );
Json_push_back (n, json_new_a (NULL, "one "));
Json_push_back (n, json_new_a (NULL, "Chinese character "));
Json_push_back (n, json_new_ I (NULL, 999999 ));

Json_char * arrjc = json_write (arrn );

CCLOG ("Json: % s, % d", arrjc, strlen (jc); </span>
Note that if you do not want a "key", set the corresponding parameter to NULL. You cannot do this in the object.

 


Special PS: If you want to output Chinese characters as they are, instead of converting them into UTF-8 encoding format, you need to disable Macros in JSONOptions. h.


[Cpp] view plaincopyprint? <Span style = "font-size: 16px;"> # define JSON_ESCAPE_WRITES </span>
<Span style = "font-size: 16px;"> # define JSON_ESCAPE_WRITES </span>
Code download

 


5-24 records: Determine the node type in libjson. c method json_type (const void * node)

Type defined

[Cpp]
# Define JSON_NULL '\ 0'
# Define JSON_STRING '\ 1'
# Define JSON_NUMBER '\ 2'
# Define JSON_BOOL '\ 3'
# Define JSON_ARRAY '\ 4'
# Define JSON_NODE '\ 5'
# Define JSON_NULL '\ 0'
# Define JSON_STRING '\ 1'
# Define JSON_NUMBER '\ 2'
# Define JSON_BOOL '\ 3'
# Define JSON_ARRAY '\ 4'
# Define JSON_NODE '\ 5'

Author: oneRain88
 

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.