构建json文件的格式

假设你是用$.getJSON();方法获取JSON数据
$.getJSON(url,{"Action":"getStudent"},function(data){})

构建JSON数据格式一(单个对象)
{"Name":"Jime","Sex":"Boy","Birthday":"1991-12-8"}
获取方式:
data.Name
data.Sex

构建JSON数据格式二(多个对象单一类型,匿名)
[{"Name":"Jime","Sex":"Boy","Birthday":"1991-12-8"},{"Name":"Jary","Sex":"Boy","Birthday":"1990-12-8"}]
获取方式:
data[0].Name;

构建JSON数据格式三(多个对象单一类型,命名)
{"Stutent":[{"Name":"Jime","Sex":"Boy","Birthday":"1991-12-8"},{"Name":"Jary","Sex":"Boy","Birthday":"1990-12-8"}]}
获取方式:
data.Student[0].Name

构建JSON数据格式四(多个对象多个类型)
{"Stutent":[{"Name":"Jime","Sex":"Boy","Birthday":"1991-12-8"},{"Name":"Jary","Sex":"Boy","Birthday":"1990-12-8"}],"Class":
{"Name":"三年级一班"}}
获取方式:
data.Student[0].Name
data.Class.Name

cocos2d-x 读取json
  1. #include "HelloWorldScene.h"  
  2. #include "json/document.h"  
  3.   
  4. Scene* HelloWorld::createScene()  
  5. {  
  6.     auto scene = Scene::create();  
  7.     auto layer = HelloWorld::create();  
  8.     scene->addChild(layer);  
  9.   
  10.     return scene;  
  11. }  
  12.   
  13. bool HelloWorld::init()  
  14. {  
  15.     if ( !Layer::init() )  
  16.     {  
  17.         return false;  
  18.     }  
  19.       
  20.     Size visibleSize = Director::getInstance()->getVisibleSize();  
  21.     Vec2 origin = Director::getInstance()->getVisibleOrigin();  
  22.   
  23.     pLabel = LabelTTF::create("""Arial", 30);  
  24.     pLabel->setPosition(visibleSize/2.0);  
  25.     this->addChild(pLabel);  
  26.   
  27.     this->readJsonByCocosAPI();  
  28.   
  29.     return true;  
  30. }  
  31.   
  32. void HelloWorld::readJsonByCocosAPI()  
  33. {  
  34.     rapidjson::Document doc;  
  35.     doc.Parse<0>(FileUtils::getInstance()->getStringFromFile("data.json").c_str());  
  36.   
  37.     // 获得第一个对象的name和age的属性  
  38.     int index = 0;  
  39.     const char *ch = doc[index]["name"].GetString();  
  40.     int iage = doc[index]["age"].GetInt();  
  41.   
  42.     std::ostringstream str;  
  43.     str << "name:";  
  44.     str << ch;  
  45.     str << ",";  
  46.     str << "age:";  
  47.     str << iage;  
  48.   
  49.     pLabel->setString(str.str());  
  50.   
  51.     // 遍历json数组  
  52.     for (int i = 0; i < doc.Size(); i ++)  
  53.     {  
  54.         const char *name= doc[i]["name"].GetString();  
  55.         int age = doc[i]["age"].GetInt();  
  56.   
  57.         log("name:%s, age:%d", name, age);  
  58.     }  
  59. }  




posted @ 2017-01-09 11:10  feizuzu  阅读(238)  评论(0)    收藏  举报