Linux 시스템 에서 어떻게 C++를 사용 하여 json 파일 을 해석 하 는 지 상세 하 게 설명 합 니 다.
일이 필요 하 니 퇴근 후에 돌아 와 서 스스로 바퀴 를 만들어 기록 한 후에 찾 아 보 세 요.
JSON(JavaScript Object Notation)은 경량급 데이터 교환 형식 으로 xml 와 유사 하 다.본 고 는 주로 Linux 에서 JSoncpp 로 json 을 분석 하 는 방법 으로 기록 하고 자 한다.
2.jsoncpp 라 이브 러 리 사용 안내
jsoncpp 를 사용 하 는 방법 은 두 가지 가 있 습 니 다.
방법 1:JSoncpp 로 생 성 된 lib 파일
위 에서 다운로드 한 JSoncpp 파일 을 압축 해제 하고 jsoncpp 에서 기본적으로 정적 링크 라 이브 러 리 를 생 성 합 니 다.프로젝트 에서 인용 하려 면 include/json 아래 의 헤더 파일 과 생 성 된.lib 파일 만 포함 하면 됩 니 다.
방법 2: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\libjson 디 렉 터 리 에 있 는 파일 은 VS 프로젝트 에 포함 되 어 있 습 니 다.VS 프로젝트 의 속성 C/C++에서 Genel 에 additional Include Directory 는 헤더 파일 디 렉 터 리 를 포함 합 니 다.\jsoncpp-src-0.5.0\include.사용 하 는 cpp 파일 에 json 헤더 파일 을 포함 하면 됩 니 다.예 를 들 어\#include"json/json.h".장 jsonreader.cpp、json_value.cpp 와 jsonwriter.cpp 세 파일 의 Precompiled Header 속성 은 Not Using Precompiled Headers 로 설정 되 어 있 습 니 다.그렇지 않 으 면 컴 파일 에 오류 가 발생 할 수 있 습 니 다.
제 가 위 에 있 는 건 다 첫 번 째 방법 을 채택 한 거 예요.
jsoncpp 사용 설명
jsoncpp 는 주로 세 가지 유형의 class:Value,Reader,Writer 를 포함한다.jsoncpp 의 모든 대상,클래스 이름 은 namespace JSon 에 있 으 며,json.h 를 포함 하면 됩 니 다.
JSon:Value 는 ANSI 형식의 문자열 만 처리 할 수 있 습 니 다.C++프로그램 이 유 니 코드 로 인 코딩 되 어 있다 면 Adapt 류 를 추가 하 는 것 이 좋 습 니 다.
3.linux 에서 jsoncpp 환경 설정
3.1 jsoncpp 원본 다운로드
github 에서 jsoncpp 를 직접 검색 하면 됩 니 다.다운로드 연결 보 내기:https://github.com/open-source-parsers/jsoncpp
3.2 구체 적 인 배치 절차
1>압축 해제 소스 코드
2>원본 디 렉 터 리 의 이전 층 에 build 디 렉 터 리 를 새로 만 들 고 컴 파일 과정 에서 생 성 된 중간 파일 을 저장 합 니 다.
3>build 디 렉 터 리 에서 cmake 를 실행 합 니 다..
4>build 디 렉 터 리 에서 make 실행
5>build 디 렉 터 리 에서 make install 실행
로 컬 jsoncpp 라 이브 러 리 보기
ls /usr/local/include ls/usr/local/lib
4.json 파일 예제 읽 기 c++사용
demo.json 파일https://blog.csdn.net/shuiyixin/article/details/89330529】
{
"age" : 21,
"friends" : {
"friend_age" : 21,
"friend_name" : "ZhaoWuxian",
"friend_sex" : "man"
},
"hobby" : [ "sing", "run", "Tai Chi" ],
"name" : "shuiyixin",
"sex" : "man"
}
test.cpp 파일
#include <iostream>
#include <json/json.h>
#include <fstream>
using namespace std;
void readFileJson()
{
Json::Reader reader;
Json::Value root;
// , demo.json
ifstream in("demo.json", ios::binary);
if (!in.is_open())
{
cout << "Error opening file
";
return;
}
if (reader.parse(in, root))
{
//
string name = root["name"].asString();
int age = root["age"].asInt();
string sex = root["sex"].asString();
cout << "My name is " << name << endl;
cout << "I'm " << age << " years old" << endl;
cout << "I'm a " << sex << endl;
//
string friend_name = root["friends"]["friend_name"].asString();
int friend_age = root["friends"]["friend_age"].asInt();
string friend_sex = root["friends"]["friend_sex"].asString();
cout << "My friend's name is " << friend_name << endl;
cout << "My friend's sex is "<<friend_sex << endl;
cout << "My friend is " << friend_age << " years old" << endl;
//
cout << "Here's my hobby:" << endl;
for (unsigned int i = 0; i < root["hobby"].size(); i++)
{
string ach = root["hobby"][i].asString();
cout << ach << '\t';
}
cout << endl;
cout << "Reading Complete!" << endl;
}
else
{
cout << "parse error
" << endl;
}
in.close();
}
int main(void)
{
readFileJson();
return 0;
}
실행 결 과 는 다음 과 같 습 니 다.5.c++를 사용 하여 json 파일 예제 쓰기
test.cpp 파일:
#include <iostream>
#include <json/json.h>
#include <fstream>
using namespace std;
void writeFileJson()
{
//
Json::Value root;
//
root["name"] = Json::Value("shuiyixin");
root["age"] = Json::Value(21);
root["sex"] = Json::Value("man");
//
Json::Value friends;
//
friends["friend_name"] = Json::Value("ZhaoWuxian");
friends["friend_age"] = Json::Value(21);
friends["friend_sex"] = Json::Value("man");
//
root["friends"] = Json::Value(friends);
//
root["hobby"].append("sing");
root["hobby"].append("run");
root["hobby"].append("Tai Chi");
//
//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("demo.json", std::ios::out | std::ios::app);
if (!os.is_open())
cout << "error:can not find or create the file which named \" demo.json\"." << endl;
os << sw.write(root);
os.close();
}
int main(void)
{
writeFileJson();
return 0;
}
실행 결 과 는 다음 과 같 습 니 다.디 렉 터 리 에 demo.json 파일 을 새로 만 들 었 고 기록 에 성공 한 것 을 볼 수 있 습 니 다.주의해 야 할 것 은:
1.기록 할 파일 이 존재 하지 않 으 면 자동 으로 파일 을 만 듭 니 다.
2.파일 이 존재 한다 면 기록 과정 은 파일 에 있 는 데 이 터 를 덮어 쓰 지 않 고 새로운 데 이 터 를 기 존 데이터 뒤에 씁 니 다.
6.문자열 로 json 해석
실제 항목 에 서 는 json 을 파일 로 해석 하 는 것 을 더 많이 사용 합 니 다.json 예제 를 문자열 로 해석 하 는 것 은 완전한 기록 을 위 한 것 입 니 다.
6.1 간단 한 json 스타일 문자열 분석 예제
#include <iostream>
#include <json/json.h>
#include <fstream>
using namespace std;
void readStrJson()
{
//
const char* str =
"{\"name\":\"shuiyixin\",\"age\":\"21\",\"sex\":\"man\"}";
// "{
// "name" : "shuiyixin",
// "age" : "21",
// "sex" : "man"
// }";
Json::Reader reader;
Json::Value root;
//
if (reader.parse(str, root))
{
string name = root["name"].asString();
int age = root["nomen"].asInt();
string sex = root["sex"].asString();
cout << name + "," << age << "," << sex << endl;
}
}
int main(void)
{
readStrJson();
return 0;
}
실행 결 과 는 다음 과 같 습 니 다.6.2 복잡 한 json 스타일 문자열 해석 예시
#include <iostream>
#include <json/json.h>
#include <fstream>
using namespace std;
void readStrProJson()
{
string strValue = "{\"name\":\"shuiyixin\",\"major\":[{\"AI\":\"MachineLearning\"},{\"AI\":\"DeepLearning\"},{\"AI\":\"ComputerVision\"}]}";
/*
{
"name":"shuiyixin",
"major":[
{
"AI":"MachineLearning"
},
{
"AI":"DeepLearning"
},
{
"AI":"ComputerVision"
}]
}
*/
Json::Reader reader;
Json::Value value;
if (reader.parse(strValue, value))
{
string out = value["name"].asString();
cout << out << endl;
const Json::Value arrayObj = value["major"];
for (unsigned int i = 0; i < arrayObj.size(); i++)
{
out = arrayObj[i]["AI"].asString();
cout << out<<endl;
}
}
}
int main(void)
{
readStrProJson();
return 0;
}
실행 결 과 는 다음 과 같 습 니 다.연결 참조:
https://www.jb51.net/article/214039.htm
https://www.jb51.net/article/214051.htm
총결산
리 눅 스 시스템 에서 어떻게 C++를 사용 하여 제 이 슨 파일 을 해석 하 는 지 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 리 눅 스 C++제 이 슨 파일 의 내용 을 분석 하려 면 예전 의 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부탁드립니다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
HDU 원활 공사 & & 원활 공사 (차 트 법)모 성 은 도시 의 교통 상황 을 조사 하여 기 존의 도시 도로 통계 표를 얻 었 고 표 에는 모든 도로 가 직접 연 결 된 도시 가 열거 되 어 있다.성 정부의 '원활 한 공사' 목 표 는 성 전체의 어느 두 도시...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.