cocos2dx jsoncpp

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+");
    
    fwrite(json_file.c_str(),json_file.size(),1,file);
    fclose(file);

}

 

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

posted @ 2015-02-05 10:58  百里抱木  阅读(272)  评论(0编辑  收藏  举报