首页 > Web开发 > 详细

cocos2dx jsoncpp

时间:2015-02-05 12:48:26      阅读:322      评论:0      收藏:0      [点我收藏+]

jsoncpp下载 http://sourceforge.net/projects/jsoncpp/

下载解压后用到的是include\json下面的头文件跟src\lib_json下的文件。

导入头文件

#include "json/json.h"

解析json

void parseJsoncpp()
{
    /*{
        "name":"more-top",
            "age":27
    }*/
    unsigned long size;
    char *file = (char *)CCFileUtils::sharedFileUtils()->getFileData("jsoncpptest.json","r",&size);
    Json::Reader reader;
    Json::Value root;
    if (!reader.parse(std::string(file),root,false))
    {
        return ;
    }
    CCLog("jsoncpptest");
    
    std::string name = root["name"].asString();
    CCLog("name = %s",name.c_str());

    int age = root["age"].asInt();
    CCLog("name = %d",age);


    //---------------------------------------
    /*[
    {"name":"more11","age":100},
    {"name":"more22","age":101}
    ]*/

    file = (char *)CCFileUtils::sharedFileUtils()->getFileData("jsoncpptest2.json","r",&size);
    if (!reader.parse(std::string(file),root,false))
    {
        return ;
    }
    CCLog("jsoncpptest2");

    size = root.size();
    for (int i = 0; i < size; i++)
    {
        std::string name = root[i]["name"].asString();
        CCLog("name = %s",name.c_str());

        int age = root[i]["age"].asInt();
        CCLog("name = %d",age);
        
    }
}

输出:

jsoncpptest
name = more-top
name = 27
jsoncpptest2
name = more11
name = 100
name = more22
name = 101

 

创建json

void createJsoncpp()
{
    //[{"age":18,"name":"cocos2dx"},{"age":20,"name":"Hello"}]
    Json::FastWriter writer;
    Json::Value root;
    Json::Value person;

    person["name"] = "cocos2dx";
    person["age"] = 18;
    root.append(person);

    person["name"] = "Hello";
    person["age"] = 20;
    root.append(person);
    string json_file = writer.write(root);

    CCLog("%s",json_file.c_str());
    char filePath[1024] = {\0};
    memset(filePath,0,sizeof(filePath));
    strcat(filePath,CCFileUtils::sharedFileUtils()->getWritablePath().c_str());
    strcat(filePath,"writeJsoncpp.json");

    FILE *file = fopen(filePath,"w+");
    if (!file)
    {
        return ;
    }
    
    fwrite(json_file.c_str(),json_file.size(),1,file);
    fclose(file);

}

 

输出:
[{"age":18,"name":"cocos2dx"},{"age":20,"name":"Hello"}]

cocos2dx jsoncpp

原文:http://www.cnblogs.com/ycclmy/p/4274232.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!