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

}

 

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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。