zoukankan      html  css  js  c++  java
  • cocos2dx jsoncpp

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

    下载解压后用到的是includejson下面的头文件跟srclib_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] = {''};
        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"}]

  • 相关阅读:
    润乾集算报表的脚本数据集
    R语言数据分析系列之五
    iOS_隐藏顶部状态栏
    机器学习(Machine Learning)&amp;深度学习(Deep Learning)资料
    Linux xargs将输出数据流转换成命令参数
    自己动手写病毒
    okhttp的简介(二)之简单封装
    Android中图形截取的方式介绍
    为何在查询中索引未被使用 (Doc ID 1549181.1)
    Giraph源代码分析(六)——Edge 分析
  • 原文地址:https://www.cnblogs.com/ycclmy/p/4274232.html
Copyright © 2011-2022 走看看