導航:首頁 > 編程語言 > jsoncpp解析json字元串

jsoncpp解析json字元串

發布時間:2021-03-05 12:14:58

『壹』 C++ json解析

C++ 解析Json——jsoncpp
JSON(javaScript Object Notation) 是一種輕量級的數據交換格式,和xml類似,本文主要對VS2008中使用Jsoncpp解析json的方法做一下記錄。
Jsoncpp是個跨平台的開源庫,下載地址:http://sourceforge.net/projects/jsoncpp/,我下載的是v0.5.0,壓縮包大約104K。

方法一:使用Jsoncpp生成的lib文件
解壓上面下載的Jsoncpp文件,在jsoncpp-src-0.5.0/makefiles/vs71目錄里找到jsoncpp.sln,用VS2008版本編譯,默認生成靜態鏈接庫。 在工程中引用,只需要包含include/json下的頭文件及生成的.lib文件即可。
如何包含lib文件:在.cpp文件中#pragma comment(lib."json_vc71_libmt.lib"),在工程屬性中Linker下Input中Additional Dependencies寫入lib文件名字(Release下為json_vc71_libmt.lib,Debug為json_vc71_libmtd.lib)

注意:Jsoncpp的lib工程編譯選項要和VS工程中的編譯選項保持一致。如lib文件工程編譯選項為MT(或MTd),VS工程中也要選擇MT(或MTd),否則會出現編譯錯誤問題,debug和release下生成的lib文件名字不同,注意不要看錯了,當成一個文件來使用(我就犯了這個錯誤)。

方法二:使用Jsoncpp包中的.cpp和.h文件
解壓上面下載的Jsoncpp文件,把jsoncpp-src-0.5.0文件拷貝到工程目錄下,將jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\include\json和jsoncpp-src-0.5.0\jsoncpp-src-0.5.0\src\lib_json目錄里的文件包含到VS工程中,在VS工程的屬性C/C++下General中Additional Include Directories包含頭文件目錄.\jsoncpp-src-0.5.0\include。在使用的cpp文件中包含json頭文件即可,如:#include "json/json.h"。將json_reader.cpp、json_value.cpp和json_writer.cpp三個文件的Precompiled Header屬性設置為Not Using Precompiled Headers,否則編譯會出現錯誤。

jsoncpp 使用詳解
jsoncpp 主要包含三種類型的 class:Value、Reader、Writer。jsoncpp 中所有對象、類名都在 namespace Json 中,包含 json.h 即可。
Json::Value 只能處理 ANSI 類型的字元串,如果 C++ 程序是用 Unicode 編碼的,最好加一個 Adapt 類來適配。

下面是從網上找的代碼示例:
1. 從字元串解析json

const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";

Json::Reader reader;
Json::Value root;
if (reader.parse(str, root)) // reader將Json字元串解析到root,root將包含Json里所有子元素
{
std::string upload_id = root["uploadid"].asString(); // 訪問節點,upload_id = "UP000000"
int code = root["code"].asInt(); // 訪問節點,code = 100
}
2. 從文件解析json

int ReadJsonFromFile(const char* filename)
{
Json::Reader reader;// 解析json用Json::Reader
Json::Value root; // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array

std::ifstream is;
is.open (filename, std::ios::binary );
if (reader.parse(is, root, FALSE))
{
std::string code;
if (!root["files"].isNull()) // 訪問節點,Access an object value by name, create a null member if it does not exist.
code = root["uploadid"].asString();

code = root.get("uploadid", "null").asString();// 訪問節點,Return the member named key if it exist, defaultValue otherwise.

int file_size = root["files"].size(); // 得到"files"的數組個數
for(int i = 0; i < file_size; ++i) // 遍歷數組
{
Json::Value val_image = root["files"][i]["images"];
int image_size = val_image.size();
for(int j = 0; j < image_size; ++j)
{
std::string type = val_image[j]["type"].asString();
std::string url = val_image[j]["url"].asString();
printf("type : %s, url : %s \n", type.c_str(), url.c_str());
}
}
}
is.close();

return 0;
}
3. 向文件中插入json

void WriteJsonData(const char* filename)
{
Json::Reader reader;
Json::Value root; // Json::Value是一種很重要的類型,可以代表任意類型。如int, string, object, array

std::ifstream is;
is.open (filename, std::ios::binary );
if (reader.parse(is, root))
{
Json::Value arrayObj; // 構建對象
Json::Value new_item, new_item1;
new_item["date"] = "2011-11-11";
new_item1["time"] = "11:11:11";
arrayObj.append(new_item); // 插入數組成員
arrayObj.append(new_item1); // 插入數組成員
int file_size = root["files"].size();
for(int i = 0; i < file_size; ++i)
root["files"][i]["exifs"] = arrayObj; // 插入原json中
std::string out = root.toStyledString();
// 輸出無格式json字元串
Json::FastWriter writer;
std::string strWrite = writer.write(root);
std::ofstream ofs;
ofs.open("test_write.json");
ofs << strWrite;
ofs.close();
}

is.close();
}

『貳』 C++解析Json字元串問題!

一、從字元串中讀取JSON
#include <iostream>
#include "json/json.h"
using namespace std;
int main()
{
//字元串
const char * str =
"{\"praenomen\":\"Gaius\",\"nomen\":\"Julius\",\"cognomen\":\"Caezar\","
"\"born\":-100,\"died\":-44}" ;
Json::Reader reader;
Json::Value root;
//從字元串中讀取數據
if (reader.parse(str,root))
{
string praenomen = root[ "praenomen" ].asString();
string nomen = root[ "nomen" ].asString();
string cognomen = root[ "cognomen" ].asString();
int born = root[ "born" ].asInt();
int died = root[ "died" ].asInt();
cout << praenomen + " " + nomen + " " + cognomen
<< " was born in year " << born
<< ", died in year " << died << endl;
}
return 0;
}

makefile文件
LIB=-L /usr/local/lib/libjson/ -ljson_linux- gcc -4.4.7_libmt
a: a.o
g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf a.o a

二、從文件中讀取JSON
PersonalInfo.json(一個存儲了JSON格式字元串的文件)

{
"name" : "Tsybius" ,
"age" :23,
"sex_is_male" : true ,
"partner" :
{
"partner_name" : "Galatea" ,
"partner_age" :21,
"partner_sex_is_male" : false
},
"achievement" :[ "ach1" , "ach2" , "ach3" ]
}
#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace std;
int main()
{
Json::Reader reader;
Json::Value root;
//從文件中讀取
ifstream is;
is.open( "PersonalInfo.json" , ios::binary);
if (reader.parse(is,root))
{
//讀取根節點信息
string name = root[ "name" ].asString();
int age = root[ "age" ].asInt();
bool sex_is_male = root[ "sex_is_male" ].asBool();
cout << "My name is " << name << endl;
cout << "I'm " << age << " years old" << endl;
cout << "I'm a " << (sex_is_male ? "man" : "woman" ) << endl;
//讀取子節點信息
string partner_name = root[ "partner" ][ "partner_name"].asString();
int partner_age = root[ "partner" ][ "partner_age" ].asInt();
bool partner_sex_is_male = root[ "partner" ]["partner_sex_is_male" ].asBool();
cout << "My partner's name is " << partner_name << endl;
cout << (partner_sex_is_male ? "he" : "she" ) << " is "
<< partner_age << " years old" << endl;
//讀取數組信息
cout << "Here's my achievements:" << endl;
for ( int i = 0; i < root[ "achievement" ].size(); i++)
{
string ach = root[ "achievement" ][i].asString();
cout << ach << '\t' ;
}
cout << endl;
cout << "Reading Complete!" << endl;
}
is.close();
return 0;
}

makefile
?
LIB=-L /usr/local/lib/libjson/ -ljson_linux- gcc -4.4.7_libmt
a: a.o
g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf a.o a

三、將信息保存為JSON格式
a.cpp

#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace std;
int main()
{
//根節點
Json::Value root;
//根節點屬性
root[ "name" ] = Json::Value( "Tsybius" );
root[ "age" ] = Json::Value(23);
root[ "sex_is_male" ] = Json::Value( true );
//子節點
Json::Value partner;
//子節點屬性
partner[ "partner_name" ] = Json::Value( "Galatea" );
partner[ "partner_age" ] = Json::Value(21);
partner[ "partner_sex_is_male" ] = Json::Value( false );
//子節點掛到根節點上
root[ "partner" ] = Json::Value(partner);
//數組形式
root[ "achievement" ].append( "ach1" );
root[ "achievement" ].append( "ach2" );
root[ "achievement" ].append( "ach3" );

//直接輸出
cout << "FastWriter:" << endl;
Json::FastWriter fw;
cout << fw.write(root) << endl << endl;
//縮進輸出
cout << "StyledWriter:" << endl;
Json::StyledWriter sw;
cout << sw.write(root) << endl << endl;

//輸出到文件
ofstream os;
os.open( "PersonalInfo" );
os << sw.write(root);
os.close();
return 0;
}

makefile
LIB=-L /usr/local/lib/libjson/ -ljson_linux- gcc -4.4.7_libmt
a: a.o
g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf a.o a

{
"achievement" : [ "ach1" , "ach2" , "ach3" ],
"age" : 23,
"name" : "Tsybius" ,
"partner" : {
"partner_age" : 21,
"partner_name" : "Galatea" ,
"partner_sex_is_male" : false
},
"sex_is_male" : true
}

『叄』 c++ json 我拿到一個json的數組,如何一個一個取出裡面的元素

可以使用jsoncpp類來處理json:

string strJ("[1,2,3]");
Json::Reader reader;
Json::Value root;
if(!reader.parse(strJ,root)){
return -1;
}
int size = root.size();
for(int i=0; i<size; ++i)
{
std::cout << root[i].asInt() << std::endl;
}

參考http://www.cnblogs.com/kex1n/archive/2011/12/02/2272328.html

『肆』 怎樣用java解析一個json字元串

public static void main(String[] args){

String temp="{'data':{'a':[{'b1':'bb1','c1':'cc1'},{'b2':'bb2','c2':'cc2'}]}}";

JSONObject jodata =JSONObject.fromObject(temp);

JSONObject joa =JSONObject.fromObject(jodata.get("data").toString());

JSONArray ja=JSONArray.fromObject(joa.get("a"));

for(int i=0;i<ja.size();i++){

JSONObject o=ja.getJSONObject(i);

if(o.get("b1")!=null){

System.out.println(o.get("b1"));

}

if(o.get("c1")!=null){

System.out.println(o.get("c1"));

}

if(o.get("b2")!=null){

System.out.println(o.get("b2"));

}

if(o.get("c2")!=null){

System.out.println(o.get("c2"));

}

}

}

註:要包含兩個jar包ezmorph-1.0.6.jar和json-lib-2.2.2-jdk15.jar,jar包在附件中

『伍』 C++ jsoncpp 幾種解析json方法求解答

還由蟗oost。。。這。。項目本身沒有上,為了個這個不合算。。然後看了下jsoncpp,雖然大了點,不過還好,就拿來用。其實解析json字元串,用他的幾個東西就足夠Json::Value 表示一個json值對象,後面會頻繁用到Json::Reader read對象,用來解析josn字元串,有reader就有writer -- Json::Writer假設有這么個json字元串,這里主要講一下帶數組這種的串,象最簡單的{"key":"value"}就不講了 - -string strJson = "{\"key1\":\"value1\",\"array\":[{\"key2\":\"value2\",\"key3\":\"aa\"},{\"key2\":\"value3\",\"key3\":\"bb\"},{\"key2\":\"value4\",\"key3\":\"cc\"}]}";一種方法:Json::Reader reader;Json::Value val;if(!reader.parse(strJson,val))return -1;std::string str = val["key1"].asString();
Json::Value obj_array = val["array"];for (int i = 0; i< obj_array.size(); i++){str = obj_array[i]["key2"].asString();
str = obj_array[i]["key3"].asString();
}一次for循環就全部解析出來了另一種,用他內建的迭代器,其實也就是他自己的一個vector<string>成員,可以自己去看json:value的定義Json::Value::Members member;//Members 這玩意就是vector<string>,typedef了而已
for (Json::Value::Members::iterator iter = member.begin(); iter != member.end(); iter++){string str_temp = (*itr)[(*iter)].asString();}} 其實這種方法和上面那個是一樣的,只不過是寫法不一樣罷了,自己看你就會發現,上面一種,不過就是取了vector的size,然後直接取值.第一次寫博,也不曉得寫啥,這東西寫著也算給是筆記吧,省的以後忘記了。

『陸』 你好,請問json中數組如何用jsoncpp解析,這個問題後來是怎麼解決的

我要堅定的活躍在這個平台,支持這個平台

『柒』 c語言 解析json字元串

你好,你用json-c庫,編譯通過了嗎?我是在ubuntu里使用json-c庫,但是無法編譯通過回,報錯 undefined reference to 'json_tokener_parse',類似的函數答沒定義的錯誤,你是怎麼調用的json-c庫?請教一下,謝謝!

『捌』 jsoncpp庫如何控制插入項在json字元串中的

引入using Newtonsoft.Json;
數據來查詢後源填充到DataTable ,再轉JsonConvert.SerializeObject
簡單例子:
DataTable dt = new DataTable();
DataColumn dcName = new DataColumn("Name");
DataColumn dcAge = new DataColumn("Age");
DataColumn dcCity = new DataColumn("City");

dt.Columns.Add(dcName);
dt.Columns.Add(dcAge);
dt.Columns.Add(dcCity);
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = "Name" + i;
dr[1] = "Age" + i;
dr[2] = "City" + i;
dt.Rows.Add(dr);
}
json = JsonConvert.SerializeObject(dt);

『玖』 小弟最近在做Json解析,在VC++利用json cpp 對json串解析,但是不知道如何解析如下所示JSON字元串,求助

JSON格式錯誤。
如果不是字元串內的引號,請不要在引號前加反斜杠。
請參考json,.org

『拾』 jsoncpp Linux詳細用法(C++) 為什麼我的jsoncpp就是讀取不出東西來呢

可以抄使襲用jsoncpp類來處理json:

string strJ("[1,2,3]");
Json::Reader reader;
Json::Value root;
if(!reader.parse(strJ,root)){
return -1;
}
int size = root.size();
for(int i=0; i<size; ++i)
{
std::cout << root[i].asInt() << std::endl;
}

閱讀全文

與jsoncpp解析json字元串相關的資料

熱點內容
外存儲存放的數據斷電會怎麼樣 瀏覽:679
怎麼給資料庫欄位建立索引 瀏覽:455
app在哪裡注冊 瀏覽:37
真相了是什麼意思網路 瀏覽:556
大數據人才培養現狀 瀏覽:458
win10不能建立遠程連接 瀏覽:685
迅捷cad看圖怎樣找本地文件 瀏覽:480
方舟最新版本 瀏覽:200
看片免費不下載網站 瀏覽:640
文件怎麼替代 瀏覽:14
有沒四級片 瀏覽:981
台灣電影 學生到老師家補習 叫什麼 瀏覽:378
快穿之小說下載TXT 瀏覽:769
三國群英傳2自動升級版 瀏覽:312
如何橋接別人路由器密碼錯誤 瀏覽:396
iso文件怎麼運行 瀏覽:303
手動鑼孔怎麼編程 瀏覽:68
傳媒女外賣員上門送逼女演員叫什麼 瀏覽:524
sbjson生成json 瀏覽:724

友情鏈接