Exemple #1
0
// Recursive function to convert JSON --> Lua table
static bool push_json_value_helper(lua_State *L, const Json::Value &value,
		int nullindex)
{
	switch(value.type()) {
		case Json::nullValue:
		default:
			lua_pushvalue(L, nullindex);
			break;
		case Json::intValue:
			lua_pushinteger(L, value.asInt());
			break;
		case Json::uintValue:
			lua_pushinteger(L, value.asUInt());
			break;
		case Json::realValue:
			lua_pushnumber(L, value.asDouble());
			break;
		case Json::stringValue:
			{
				const char *str = value.asCString();
				lua_pushstring(L, str ? str : "");
			}
			break;
		case Json::booleanValue:
			lua_pushboolean(L, value.asInt());
			break;
		case Json::arrayValue:
			lua_newtable(L);
			for (Json::Value::const_iterator it = value.begin();
					it != value.end(); ++it) {
				push_json_value_helper(L, *it, nullindex);
				lua_rawseti(L, -2, it.index() + 1);
			}
			break;
		case Json::objectValue:
			lua_newtable(L);
			for (Json::Value::const_iterator it = value.begin();
					it != value.end(); ++it) {
#ifndef JSONCPP_STRING
				const char *str = it.memberName();
				lua_pushstring(L, str ? str : "");
#else
				std::string str = it.name();
				lua_pushstring(L, str.c_str());
#endif
				push_json_value_helper(L, *it, nullindex);
				lua_rawset(L, -3);
			}
			break;
	}
	return true;
}
Exemple #2
0
bool Tree::ParseFromJsonInternal(const Json::Value &json)
{
    size_t index = 0;
    for (Json::Value::const_iterator p = json.begin(); p != json.end(); ++p) {
        const Json::Value &j = *p;
        std::string key = p.name();
        if (key.empty()) {
            std::ostringstream s;
            s << '[' << index++ << ']';
            key = s.str();
        }

        std::string full_path = GetFullPath(key);
        if (j.isArray() || j.isObject()) { // Go recursively.
            Tree *child = new Tree(full_path, key, std::string());
            _children.insert(std::make_pair(key, child));

            if (!child->ParseFromJsonInternal(j)) {
                return false;
            }

            continue;
        }

        std::ostringstream s;
#ifdef JSON_HAS_INT64
        if (j.isInt64() ) { s << j.asInt64();   } else
        if (j.isUInt64()) { s << j.asUInt64();  } else
#endif
        if (j.isInt()   ) { s << j.asInt();     } else
        if (j.isUInt()  ) { s << j.asUInt();    } else
        if (j.isDouble()) { s << j.asDouble();  } else
                          { s << j.asString();  }

        const std::string &value = s.str();
        Tree *child = new Tree(full_path, key, value);
        _children.insert(std::make_pair(key, child));
    }

    return true;
}