基于VS2013MFC的JSON文件的写入和解析

来源:互联网 发布:外国人抢购的国货知乎 编辑:程序博客网 时间:2024/05/18 16:57

1. JSON文件的写入

类似于一般文本文件的写入。

CFile cf;if (cf.Open(strFileWeather, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyNone) == FALSE)  //strFileWeather是JSON文件名{           return ;}char cReadBuffer[4096] = {0};cf.Write(cReadBuffer, 4089);cf.Close();

2. JSON文件的解析

添加头文件

#include <Winnls.h>#pragma comment(lib,"Kernel32.lib")#include<fstream>

添加”lib_json.lib”

添加 链接器->输入->附加依赖项 lib_json.lib

添加代码

    CFile cf;    if (cf.Open(strJSONFile, CFile::modeRead | CFile::shareDenyNone) == FALSE)    {        return;    }    DWORD length = (DWORD)cf.GetLength();    if (length < 1)    {        cf.Close();        return;    }    char* pdata = new char[length];    if (pdata == NULL)    {        cf.Close();        return;    }    if (cf.Read(pdata, length) != length)    {        delete[]pdata;        cf.Close();        return;    }    cf.Close();    std::string ss = pdata;         //获取数据给字符串    delete[]pdata;    Json::Reader reader;    Json::Value root;    if (!reader.parse(ss, root, false))    {        return;     //解析错误    }    CString str;    Json::Value item, item2, item3;    #define def_weather_readjson_get_str2(a, b, c)  c=item2[a][b].asString().c_str();    item = root["Net_Header"]; //NetHeader为JSON文件首字符串,具有标识意义    int i, j, size3, size2, size = item.size();    if (size < 1)    {        return;    }     CString ct_str = ct.Format(_T("%Y-%m-%d"));    i = 0;    item2 = item[i]["daily_forecast"];    size2 = item2.size();    for (j = 0; j < size2; j++)     //里面有七天的天气,找到今天的天气    {        def_weather_readjson_get_str2(j, "date", str);        if (str == ct_str)            break;    }    if (j == size2)    {        return;    }    //天气    item3 = item2[j]["cond"];       //从今天中找到天气     size3 = item3.size();    if (size3 < 1)    {        return;    }    TCHAR weather[32];    int temp_d, temp_n;    str = item3["code_d"].asString().c_str(); //今天天气code_d对应的字符串    str = item3["code_n"].asString().c_str(); //今天天气code_n对应的字符串

注:源代码以获取天气信息为例;

原创粉丝点击