其他分享
首页 > 其他分享> > json文件解析

json文件解析

作者:互联网

Tool_json.h

#pragma once
#include "json.h"

class Tool_json
{
public:
    Tool_json();
    ~Tool_json();
public:
    //二进制读取file_path路径下的json文件,保存到m_JsonRoot
    int Init(const std::string& file_path);
    //获取指定关键字对应的std::string信息
    int GetConfigInfo(const std::string& key, std::string& value);
    //获取指定关键字对应的int信息
    int GetConfigInfo(const std::string& key, int& value);
    //获取指定关键字对应的double信息
    int GetConfigInfo(const std::string& key, double& value);
protected:
    //json文件根节点对象
    Json::Value m_JsonRoot;
};

Tool_json.cpp

#include "Tool_json.h"
#include "errorDefine.h"
#include <sstream>
#include <fstream>
#include <iostream>

#include "km_log.h"


Tool_json::Tool_json()
{
}

Tool_json::~Tool_json()
{
}

int Tool_json::Init(const std::string & file_path)
{
    Json::Reader json_reader;
    std::ifstream in(file_path, std::ios::binary);
    if (!in.is_open()) {
        KM_APP_LOG_ERROR("Tool_json::Init jsonFile fail.file_path:" << file_path);
        return TOOLJSON_INIT_ERROR;
    }

    int end_parse = 1;
    do {
        bool ret = json_reader.parse(in, m_JsonRoot);
        if (ret != true) {
            end_parse = 0;
            break;
        }
    } while (1);
    in.close();
    KM_APP_LOG_INFO("Tool_json::Init successed.file_path:" << file_path);
    return 1;
}

int Tool_json::GetConfigInfo(const std::string& key, std::string& value)
{
    if (!m_JsonRoot[key].isString()) 
    {
        KM_APP_LOG_ERROR("Tool_json::GetConfigInfo fail:" << key);
        return TOOLJSON_GET_ERROR;
    }

    value = m_JsonRoot[key].asString();
    return RET_SUCCESS;
}

int Tool_json::GetConfigInfo(const std::string& key, int& value)
{
    if (!m_JsonRoot[key].isInt())
    {
        KM_APP_LOG_ERROR("ConfigMgr::GetConfigInfo root is not key.key:" << key);
        return TOOLJSON_GET_ERROR;
    }

    value = m_JsonRoot[key].asInt();
    return RET_SUCCESS;
}

int Tool_json::GetConfigInfo(const std::string & key, double & value)
{
    if (!m_JsonRoot[key].isDouble())
    {
        KM_APP_LOG_ERROR("ConfigMgr::GetConfigInfo root is not key.key:" << key);
        return TOOLJSON_GET_ERROR;
    }
    
    value = m_JsonRoot[key].asInt();
    return RET_SUCCESS;
}

 

标签:std,文件,include,string,int,Tool,json,解析
来源: https://www.cnblogs.com/deep-wj/p/16382993.html