zoukankan      html  css  js  c++  java
  • c++ json字符串转换成map管理

    在cocos2dx for lua中,我们经常通过lua的table传入c++使用,然后早c++层操作数据。

    实现步骤大致如下:

    table->string->c++层->通过rapidjson解析->存放在map中管理

    在lua中,转换table大致如下

    local tbl = {}

    tbl["fang"] = 1

    tbl["jian"] = 1.4

    tbl["heng"] = true

    tbl["fjh"] = 12345677

    tbl["what"] = "fuck"

    local str = json.encode(tbl)

    --打印str:

    {"fang":1,"jian":1.4,"heng":true,"fjh":12345677,"what":"fuck"}

    将str传入c++层,通过rapidjson::Document进行解析str,然而,json字符串中的数据类型不确定,

    但触控已经封装好了一个CCLValue类给我们使用,它能存放任何值简单的数据类型进行保存,然后需要的

    时候再进行获取。这里提供CCLValue.h和CCLValue两个文件下载:

    http://pan.baidu.com/s/1c06Z0xM

    以下方法是通过字符串转换成map保存的方法:

    map<string,LValue> TestLValue::jsonStringToMap(const string& jsonString)

    {

        rapidjson::Document doc;

        doc.SetObject();

        doc.Parse<rapidjson::kParseDefaultFlags>(jsonString.c_str());

        

        map<string,LValue> m;

        

        for(rapidjson::Value::MemberIterator iter = doc.MemberonBegin();iter != doc.MemberonEnd();iter++)

        {

            const char * key = iter->name.GetString();

            const rapidjson::Value& val = iter->value;

            if(val.IsDouble())

                m.insert(make_pair(key, LValue(val.GetDouble())));

            else if(val.IsBool())

                m.insert(make_pair(key, LValue(val.GetBool())));

            else if(val.IsInt())

                m.insert(make_pair(key, LValue(val.GetInt())));

            else if(val.IsInt64())

                m.insert(make_pair(key, LValue(val.GetInt64())));

            else if(val.IsString())

                m.insert(make_pair(key, LValue(val.GetString())));

        }

        return m;

    }

    过程很简单,返回值的map<string,LValue>中的LValue的值需要判断其数据类型然后进行获取

    if (it->second.getType()==LValue::Type::DOUBLE) {

      double value = it->second.asDouble();

    else if (it->second.getType()==LValue::Type::INTEGER) {

      int value = it->second.asInt();

    .

    .

    .

    还有float、string、int64、bool、int64就不一一细写了

    转载请注明出处,from 博客园 HemJohn

  • 相关阅读:
    Java中数据结构对应mysql数据类型
    pom.xml设置字符编码
    java.lang.IllegalStateException: Service id not legal hostname (/test-gw-aqa)
    org.springframework.context.ApplicationContextException: Unable to start web server; nested exceptio
    nacos的三种部署方式
    o.s.c.a.n.c.NacosPropertySourceBuilder : get data from Nacos error,dataId:application-dev.yaml
    java使用split注意事项
    《非暴力沟通》之读书心得
    js存储token
    SpringCloudGateWay之网关跨域问题解决
  • 原文地址:https://www.cnblogs.com/HemJohn/p/4946434.html
Copyright © 2011-2022 走看看