10.cocos2d-x文件读写、Json操作

文件读写操作




        //1.获取可操作的程序文件夹
        std::string path1 = FileUtils::getInstance()->getWritablePath()+"user.txt";
        CCLOG(path1.c_str());//C:/Users/laixiao/AppData/Local/Test3/

        //2.写入数据到文件
        std::string str0 = "laixiao赖肖";//会有中文乱码(cocos2d-x默认utf-8编码;可是内容是gb2312编码)
        FileUtils::getInstance()->writeStringToFile(str0, path1);

        //3.从文件读取一个字符串
        std::string str1 = FileUtils::getInstance()->getStringFromFile(path1);
        CCLOG(str1.c_str());

        //一:反序列化过程
        /*
            使用#include "spine/Json.h"
            新建f1.txt文件,json格式的内容,保存到Data/f1.txt
            [
                {"id":10000,"name":"记得"},
                {"id":10001,"name":"用"},
                {"id":10002,"name":"utf-8无Bom格式"},
                {"id":10003,"name":"编码"},
                {"id":10004,"name":"保存到工程目录"},
                {"id":10004,"name":"Resource文件夹res文件夹下"},
            ]
        */

        //直接读取工程目录下的文件
        std::string str2 = FileUtils::getInstance()->getStringFromFile("Data/f1.txt");
        CCLOG(str2.c_str());

        //字符串转换为json
        Json* f1Json = Json_create(str2.c_str());
        //获取Json数组的一个元素
        Json* node = f1Json->child;
        while (node)
        {
            //获取id,转换为int类型
            int id = Json_getItem(node,"id")->valueInt;
            //获取id,转换为String类型
            std::string name = Json_getItem(node,"name")->valueString;
            CCLOG(name.c_str());

            node = node->next;
        }

        //二:序列化过程
        std::string str3 = "{\"id\":1000,\"name\":\"laixiao\"}";
        CCLOG(str3.c_str());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值