Cocos2d-x数据篇02:Json数据操做

【前言】编程

在游戏中使用Json来储存数据,既方便读取,又方便管理。json

好比Cocos Studio 1.6以前版本导出的资源扩展名就是 .ExportJson 格式的。api

Cocos2d-x 3.x 加入了rapidjson库用于json解析。位于external/json下。数组

本节要介绍的就是:如何使用rapidjson库来操做处理json文件。app


【Json简介】less

摘自:http://www.w3school.com.cn/json/index.asp编程语言


一、什么是Json?函数

> Json 指的是 JavaScript 对象表示法(JavaScript Object Notation)。ui

> Json 是轻量级的存储和文本数据交换格式,相似XML。编码

> Json 比 XML 更小、更快,更易解析。

> Json 具备自我描述性,更易理解。

> Json 独立于语言 * 。

    *  Json使用 JavaScript 语法来描述数据对象,可是 Json 仍然独立于语言和平台。

    *  Json解析器和 Json 库支持许多不一样的编程语言。


二、语法规则

JSON 语法是 JavaScript 对象表示法语法的子集。

(1)数据在“名称/值对”中,即 键值对(key-value)形式。

(2)每条数据由“逗号”分隔。

(3)“花括号”{ } 保存 对象。

(4)“方括号”[ ] 保存 数组。


2.一、名称/值对

JSON 数据的书写格式是:名称/值对(键值对 key-value)。

名称/值对,包括字段名称(在双引号中),后面写一个冒号,而后是值。

1
2
3
4
5
6
7
//
     // "名称" : "值"
     "firstName"  "John"
      
     // 错误。名称必须加双引号""
     name :  "Alice"
//


2.二、值

JSON的值能够是:

> null

> 逻辑值(boolean)

> 数字(number)

> 字符串(string,在双引号 " " 中)

> 数组(在方括号 [ ] 中)

> 对象(在花括号 { } 中)

PS:即“名称/值对”数据中,其名称的冒号“ : ”后面对应的值能够不是字符串,也能够是数字、数组、对象等。


2.三、对象

JSON 对象在花括号中书写:{ } 。

对象能够包含多个名称/值对( 能够理解为对象的 属性名/属性值 )。

PS:名称必需要加双引号" ",而且对象中只能包含名称/值对的形式,不能只有一个值。

以下所示:

1
2
3
4
5
6
7
8
9
10
//
    
         "name" : "John" ,        // 正确
         "age" :23,             // 正确
         "array"  : [1,2,3,4],  // 正确。值能够为数组形式
  
         "hello world" ,        // 错误。不能仅为一个值
         name :  "John"         // 错误。名称必须加双引号"name"
     }
//


2.四、数组

JSON 数组在方括号中书写:[ ] 。

数组可包含多个值(能够为null、逻辑值、数字、字符串、对象、数组)。

PS:数组中只能包含值的形式,不能为名称/值的形式。

以下所示:

1
2
3
4
5
6
7
8
9
10
11
12
//
     [
         true ,                        // 逻辑值Bool
         123,                         // 数字Number
         "888" ,                       // 字符串String
         "hello world" ,               // 字符串String
         { "name" : "alice" "age" :23},  // 对象Object
         [1,2,3,4],                   // 数组Object
  
         "name"  "John"              // 错误。不能为 名称/值 的形式
     ]
//


【rapidjson】

Cocos2d-x 3.x 加入了 rapidjson库,用于Json解析。位于external/json下。

只支持标准的Json格式,一些非标准的Json格式不支持。一些经常使用的解析方法须要本身封装。注意判断解析节点是否存在。

PS:解析的Json文件,根节点必须为对象、或数组。否则没法解析。

以下所示:

wKioL1TgJnWS2IFTAAHBNUHJwmo917.jpg

一、添加头文件

若是只用于解析Json文件,只要前2行的头文件便可。

1
2
3
4
5
6
7
8
9
10
//
     #include  "json/rapidjson.h"
     #include  "json/document.h"
     #include  "json/writer.h"
     #include  "json/stringbuffer.h"
     //#include "json/filestream.h"
     //#include "json/prettywriter.h"
  
     using  namespace  rapidjson;  // 命名空间
//


二、Json数据解析

Cocos封装的 rapidjson库,只能解析对象格式、或数组格式的Json文件。


2.一、解析对象格式的Json

Json文件中的数据,根节点为一个对象,全部属性在大花括号 { } 中。

对象中的数据,经过 名称/值 的形式进行访问。

Json文件内容以下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//
{
     "hello"  "world" ,
     "t"      true ,
     "f"      false ,
     "n"      : null,
     "i"      : 123,
     "pi"     : 3.1416,
     "array"  : [1, 2, 3, 4],
     "object" : {
         "name"  "alice" ,
         "age"  : 23
     }
}
//

Json解析使用举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
//[1] 读取json文件内容
     std::string str = FileUtils::getInstance()->getStringFromFile( "testJson.json" );
     CCLOG( "%s" , str.c_str());
  
//[2] 建立用于处理json代码的类
     // 建立rapidjson::Document类:用于操做json代码
     rapidjson::Document d;
  
//[3] 解析json文件内容
     // 其中 rapidjson::kParseDefaultFlags = 0,默认方式
     d.Parse<rapidjson::kParseDefaultFlags>(str.c_str());
     // d.Parse<0>(str.c_str());  // 也能够直接写<0>
  
//[4] 判断解析是否出错
     if  (d.HasParseError()) {
         CCLOG( "GetParseError %s\n" ,d.GetParseError());
         return ;
     }
  
//[5] 获取json中的数据
     // 判断json文件是否为对象格式
     if  (d.IsObject()) {
  
         // 是否有 "hello" 属性
         if  (d.HasMember( "hello" )) {
             CCLOG( "%s" , d[ "hello" ].GetString());  // 方式一:直接获取
         }
         // 是否有 "i" 属性
         if  (d.HasMember( "i" )) {
             rapidjson::Value& i = d[ "i" ];         // 方式二:保存为rapidjson::Value&
             CCLOG( "%d" , i.GetInt());
         }
  
         // 数组
         if  (d.HasMember( "array" )) {
             // 获取数组中的元素:d["array"][i]
             for  ( int  i = 0; i < d[ "array" ].Size(); i++) {
                 CCLOG( "%d : %d" , i, d[ "array" ][i].GetInt());
             }
  
//            // 也能够这么写
//            rapidjson::Value& array = d["array"];
//            for (int i = 0; i < array.Size(); i++) {
//                CCLOG("%d : %d", i, array[i].GetInt());
//            }
         }
  
         // 对象
         if  (d.HasMember( "object" )) {
             // 判断 "object" 属性对应的值,是否为一个对象
             if  (d[ "object" ].IsObject()) {
                 // 转化为 rapidjson::Value&
                 rapidjson::Value& object = d[ "object" ];
                 CCLOG( "%s" , d[ "object" ][ "name" ].GetString());
                 CCLOG( "%d" , object[ "age" ].GetInt());
             }
         }
     }
//

控制台输出结果:

wKioL1TgmqTCss9tAABlZCNdqNY123.jpg

2.二、解析数组格式的Json

Json文件中的数据,根节点为一个数组,全部元素在一个大方括号 [ ] 中。

数组中的数据,经过下标的形式访问元素值(下标从0开始)。

Json文件内容以下:

1
2
3
4
5
6
7
8
9
10
//
     [
         true ,
         123,
         "888" ,
         "hello world" ,
         { "name"  "alice" "age"  : 23},
         [1,2,3,4]
     ]
//

Json解析使用举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
//[1] 读取json文件内容
     std::string str = FileUtils::getInstance()->getStringFromFile( "testJson.json" );
     CCLOG( "%s" , str.c_str());
  
//[2] 建立用于处理json代码的类
     // 建立rapidjson::Document类:用于操做json代码
     rapidjson::Document d;
  
//[3] 解析json文件内容
     // 其中 rapidjson::kParseDefaultFlags = 0,默认方式
     d.Parse<rapidjson::kParseDefaultFlags>(str.c_str());
     // d.Parse<0>(str.c_str());  // 也能够直接写<0>
  
//[4] 判断解析是否出错
     if  (d.HasParseError()) {
         CCLOG( "GetParseError %s\n" ,d.GetParseError());
         return ;
     }
  
//[5] 获取json中的数据
     // 判断json文件是否为数组格式
     if  (d.IsArray()) {
          
         rapidjson::Value& array = d;
          
         for  ( int  i = 0; i < array.Size(); i++) {
  
             if  (d[i].IsBool()) {    // 逻辑值
                 CCLOG( "%d is Bool : %d" , i, array[i].GetBool());
             }
             if  (d[i].IsNumber()) {  // 数字
                 CCLOG( "%d is Number : %d" , i, array[i].GetInt());
             }
             if  (d[i].IsString()) {  // 字符串
                 CCLOG( "%d is String : %s" , i, array[i].GetString());
             }
             if  (d[i].IsObject()) {  // 对象
                 rapidjson::Value& object = d[i];
                 CCLOG( "%d is Object : %s" , i, array[i][ "name" ].GetString());
                 CCLOG( "%d is Object : %d" , i, object[ "age" ].GetInt());
             }
             if  (d[i].IsArray()) {   // 数组
                 for  ( int  j = 0; j < array[i].Size(); j++) {
                     CCLOG( "[%d,%d] is Array : %d" , i, j, array[i][j].GetInt());
                 }
             }
         }
     }
//

控制台输出结果:

wKiom1TgxR-BbIOsAACJwvJESN0200.jpg

三、Json数据存储

3.一、存储为对象格式的Json

使用举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
//[1] 建立用于处理json代码的类
     // 建立rapidjson::Document类:用于操做json代码
     rapidjson::Document d;
  
//[2] 获取分配器
     rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
  
//[3] 设置为对象格式 SetObject
     d.SetObject();
  
//[4] 添加数据
     //[4.1] 往json对象中添加数据:名称/值对
     rapidjson::Value object(rapidjson::kObjectType);  // 建立对象
  
     object.AddMember( "int" , 1, allocator);          // 添加 "int" : 1
     object.AddMember( "double" , 1.1, allocator);     // 添加 "double" : 1.1
     object.AddMember( "hello" "world" , allocator);  // 添加 "hello" : "world"
  
     //[4.2] 往json数组中添加数据:值
     rapidjson::Value array(rapidjson::kArrayType);  // 建立数组
  
     rapidjson::Value str(rapidjson::kStringType);   // 字符串
     rapidjson::Value obj(rapidjson::kObjectType);   // 对象
     str.SetString( "hello" );  // 设置str的值
     obj.AddMember( "name" "alice" , allocator);
     obj.AddMember( "age" , 23, allocator);
  
     array.PushBack(123, allocator);    // 添加数字
     array.PushBack( "888" , allocator);  // 添加字符串,方式一
     array.PushBack(str, allocator);    // 添加字符串,方式二
     array.PushBack(obj, allocator);    // 添加对象
  
     //[4.3] 往对象格式的json文件中添加数据
     d.AddMember( "hello" "world" , allocator);
     d.AddMember( "object" , object, allocator);
     d.AddMember( "array" , array, allocator);
  
//[5] 将json数据写入文件中
     StringBuffer buffer;
     rapidjson::Writer<StringBuffer> writer(buffer);
     d.Accept(writer);
     CCLOG( "%s" , buffer.GetString());
  
     FILE * file =  fopen ( "/soft/cocos2d-x-3.4/projects/Demo34/Resources/testJson.json" "wb" );
     if (file) {
         fputs (buffer.GetString(), file);
         fclose (file);
     }
//

控制台输出结果:

1424852036210171.jpg

Json代码整理一下,以下:

1
2
3
4
5
6
7
//
     {
         "hello"  "world" ,
         "object" : {  "int" :1,  "double" :1.1,  "hello" : "world"  },
         "array"  : [ 123,  "888" "hello" , { "name" : "alice" "age" :23} ]
     }
//


3.二、存储为数组格式的Json

使用方法与存储为对象格式相似。

使用举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//
//[1] 建立用于处理json代码的类
     // 建立rapidjson::Document类:用于操做json代码
     rapidjson::Document d;
  
//[2] 获取分配器
     rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
  
//[3] 设置为数组格式 SetArray
     d.SetArray();
  
//[4] 添加数据
     rapidjson::Value object(rapidjson::kObjectType);
     object.AddMember( "name" "alice" , allocator);
     object.AddMember( "age" , 23, allocator);
  
     d.PushBack(123, allocator);
     d.PushBack( "hello" , allocator);
     d.PushBack(object, allocator);
  
//[5] 将json数据写入文件中
     StringBuffer buffer;
     rapidjson::Writer<StringBuffer> writer(buffer);
     d.Accept(writer);
     CCLOG( "%s" , buffer.GetString());
  
     FILE * file =  fopen ( "/soft/cocos2d-x-3.4/projects/Demo34/Resources/testJson.json" "wb" );
     if (file) {
         fputs (buffer.GetString(), file);
         fclose (file);
     }
//

控制台输出结果:

wKiom1Tg3sKi2sZfAAAcbwrQBbk511.jpg

四、Json数据修改

以对象格式的Json文件为例。

Json文件内容以下:

1
2
3
4
5
6
7
//
     {
         "hello"  "world" ,
         "array"  : [1, 2, 3, 4],
         "object" : { "name" : "alice" "age" :23 }
     }
//

对Json文件数据进行修改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//
//[1] 读取json文件内容
     std::string str = FileUtils::getInstance()->getStringFromFile( "/soft/cocos2d-x-3.4/projects/Demo34/Resources/testJson.json" );
  
//[2] 建立用于处理json代码的类、获取分配器、解析json文件内容
     rapidjson::Document d;
     rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
     d.Parse<0>(str.c_str());
  
//[3] 判断解析是否出错
     if  (d.HasParseError()) {
         CCLOG( "GetParseError %s\n" ,d.GetParseError());
         return ;
     }
  
//[4] 修改Json文件的数据
     // 修改: "hello" 的值 "hello":"hehe"
     d[ "hello" ].SetString( "hehe" );
     // 添加:对象的数据 "newdata":"888"
     d.AddMember( "newdata" "888" , allocator);
     // 删除:对象中的数据 "object"
     d.RemoveMember( "object" );
  
//[5] 将json数据从新写入文件中
     StringBuffer buffer;
     rapidjson::Writer<StringBuffer> writer(buffer);
     d.Accept(writer);
     CCLOG( "%s" , buffer.GetString());
  
     FILE * file =  fopen ( "/soft/cocos2d-x-3.4/projects/Demo34/Resources/testJson.json" "wb" );
     if (file) {
         fputs (buffer.GetString(), file);
         fclose (file);
     }
//

控制台输出结果:

wKioL1Tg5EKDAW0uAAAjj90CjHg342.jpg


【经常使用操做】

经常使用操做以下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//
// 建立用于处理json文件的类
     rapidjson::Document d;
// 获取分配器
     rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
// 判断是否解析错误
     d.HasParseError();
     d.GetParseError();
  
// 解析json文件
     d.Parse<0>( const  Ch *str);
// 将数据写入json文件
     StringBuffer buffer;
     rapidjson::Writer<StringBuffer> writer(buffer);
     d.Accept(writer);
  
     FILE * file =  fopen ( "/soft/cocos2d-x-3.4/projects/Demo34/Resources/testJson.json" "wb" );
     if (file) {
         fputs (buffer.GetString(), file);
         fclose (file);
     }
  
// json数组操做
// json数组
     rapidjson::Value& array = d[ "array" ];
     rapidjson::Value array(rapidjson::kArrayType);
  
     array.PushBack(T value, allocator);    // 向数组中添加值
     array.Size();   // 数组元素个数
     array.Clear();  // 清空数组元素
     array.Empty();  // 判断数组元素是否为空
  
// json对象操做
     // json对象
相关文章
相关标签/搜索