C 讀取json檔案內容

2021-08-20 10:26:01 字數 2791 閱讀 6947

int main(int argc, const char* argv)

//return runtest(opts);

//}//catch (const std::exception& e)

//std::string strvalue = ",,]}";

//json::reader reader;//json解析  

//json::value value;//表示乙個json格式的物件  

//if (reader.parse(strvalue, value))//解析出json放到json中區  

////}

//json::value jsonroot; //定義根節點

//json::value jsonitem; //定義乙個子物件

//jsonitem["item1"] = "one"; //新增資料

//jsonitem["item2"] = 2;

//清除jsonitem

//jsonitem["item1.0"] = 1.0;

//jsonitem["item2.0"] = 2.0;

//std::cout << jsonroot.tostyledstring() << std::endl; //輸出到控制台

//std::ofstream ofs; //標準輸出流

"sample.json"); //建立檔案

//ofs << jsonroot.tostyledstring(); //輸出

//std::ifstream ifs; //標準輸入流

"sample.json");

//json::charreaderbuilder builder;

//builder["collectcomments"] = false;

//jsoncpp_string errs;

//if (!parsefromstream(builder, ifs, &jsonroot, &errs)) //從ifs中讀取資料到jsonroot

////std::cout << jsonroot.tostyledstring() << std::endl; //輸出到控制台

//std::string jsonstr = jsonroot.tostyledstring(); //json字串

//json::charreaderbuilder builder;

//builder["collectcomments"] = false;

//jsoncpp_string errs;

//json::charreader* reader = builder.newcharreader();

//if (!reader->parse(jsonstr.data(), jsonstr.data() + jsonstr.size(), &jsonroot, &errs)) //從jsonstr中讀取資料到jsonroot

////std::cout << jsonroot.tostyledstring() << std::endl; //輸出到控制台

//for (auto i = 0; i < jsonroot.size(); i++)//遍歷陣列

////

//}std::cout << "測試json寫入" << std::endl;

json::value jsonroot;

json::value jsonitem;

jsonitem["item1"] = "第乙個條目";

jsonitem["item2"] = "第二個條目";

jsonitem["item3"] = 3;

jsonitem.clear();//清除上面已經賦值的項

jsonitem["first"] = "1";

jsonitem["second"] = 2;

jsonitem["third"] = 3.0f;

std::cout << jsonroot.tostyledstring() << std::endl;

std::cout << "測試json寫入到檔案" << std::endl;

std::ofstream ofs;

ofs.open("test1.json");

ofs << jsonroot.tostyledstring();

ofs.close();

std::cout << "測試json讀取" << std::endl;

std::string sjson = jsonroot.tostyledstring();

jsonroot.clear();

json::reader jsonreader;

if (!jsonreader.parse(sjson, jsonroot))

for (auto it = jsonroot.begin();

it != jsonroot.end();

it++)

}std::cout << "測試讀取json檔案" << std::endl;

std::ifstream ifs;

ifs.open("test1.json");

jsonroot.clear();

if (!jsonreader.parse(ifs, jsonroot))

ifs.close();

for (auto it = jsonroot.begin();

it != jsonroot.end();

it++)

}system("pause");

return 0;

}

C讀取檔案內容

include include include include include char getfilecontent const char psfilename int nfilelen lseek pf,0,seek end lseek pf,0,seek set char psfilecont...

CSharp讀取json配置檔案內容

步驟 讀取配置檔案轉換成字串,如下 string contents system.io.file.readalltext config.json 注意 該語句會丟擲檔案不存在異常。使用newtonsoft.json將json字串轉換成類的物件,完整 如下所示 public class init ca...

用C讀取json檔案

a jconf t read jconf const char file 確定檔案大小,並將讀取指標移回檔案開始 fseek f,0,seek end long pos ftell f fseek f,0,seek set if pos 0 if pos max conf size 根據檔案大小申請...