c++使用jsoncpp读取json文件

准备

  1. Visual studio 2019
  2. jsoncpp 1.8.4
  3. c++语言

代码

#include 
#include 
#include
#include
#include 
#include 
#include "json/json.h"

//链接,放在源码相同文件夹下
#pragma comment(lib,"json_vc71_libmtd.lib")

std:: string UTF8ToGB(const char* str)
{
     

    //UTF-8转换GB
    //UTF8ToGB(data[i][j].asString().data())  string转char *str
    std::string result;
    WCHAR* strSrc;
    LPSTR szRes;

    int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
    strSrc = new WCHAR[i + 1];
    MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);

    i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
    szRes = new CHAR[i + 1];
    WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);

    result = szRes;
    delete[]strSrc;
    delete[]szRes;
    return result;
}

void ReadJsonFromFile(const char* file)
{
     
    std::string line, jsonStr;
    std::ifstream ifs(file);

    assert(ifs.is_open());

    while (getline(ifs, line))
    {
     
        jsonStr.append(line);
    }
    ifs.close();

    bool res;
    JSONCPP_STRING errs;
    Json::Value root, rows, data;

    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.length(), &root, &errs);
    if (!res || !errs.empty())
    {
     
        std::cout << "ReadJsonFromString error! " << errs << std::endl;
    }

    std::cout << "root.size() = " << root.size() << std::endl;

    data = root["data"];
    std::cout << "data: \n"<<data<<std::endl;
    std::cout << data[0].size() << std::endl;
    std::cout << data[0][0]<< std::endl;
    std::cout << UTF8ToGB(data[0][0].asString().data()) << std::endl;
}

int main()
{
     
    std::string jsonStr;
    ReadJsonFromFile("FaceFeature.json");
    return 0;
}

测试json文件

{
     
  "code": 0,
  "msg": "",
  "count": 2,
  "data": [
    [
      "154 工单",
      "Doe",
      "13585486456",
      "center",
      "aa",
      "aa",
      "aa",
      "aa"
    ],
    {
     
      "id": "154",
      "username": "oe",
      "city": "13585456",
      "sign": "ceter",
      "classify": "a",
      "experience": "a",
      "score": "a",
      "wealth": "a"
    }
  ]
}

文件结构

c++使用jsoncpp读取json文件_第1张图片

结果详情

c++使用jsoncpp读取json文件_第2张图片

中文处理

来源博客:
jsoncpp处理中文乱码
其他资源:
源码以及jsoncpp文件包

你可能感兴趣的:(c++,c++,json,jsoncpp)