nlohmann源码仓库:https://github.com/nlohmann/json 使用方式:将其nlohmann文件夹加入,包含其头文件json.hpp即可 demo
# include <iostream>
# include "nlohmann/json.hpp"
# include <vector> using json = nlohmann:: json;
struct Address
{ std:: string street; std:: string city;
} ;
struct Person
{ std:: string name; int age; bool isStudent; std:: vector< int > grades; Address address; std:: vector< Address> addresses;
} ; int main ( )
{ Person person; person. name = "John" ; person. age = 30 ; person. isStudent = false ; person. grades = { 90 , 85 , 92 } ; person. address = { "123 Main St" , "Anytown" } ; person. addresses = { { "456 Elm St" , "Somewhere" } , { "789 Oak St" , "Nowhere" } } ; json jsonData = { { "name" , person. name} , { "age" , person. age} , { "isStudent" , person. isStudent} , { "grades" , person. grades} , { "address" , { { "street" , person. address. street} , { "city" , person. address. city} } } , { "addresses" , json:: array ( ) } } ; jsonData[ "age" ] = 20 ; for ( const auto & addr : person. addresses) { jsonData[ "addresses" ] . push_back ( { { "street" , addr. street} , { "city" , addr. city} } ) ; } std:: string jsonString = jsonData. dump ( 4 ) ; std:: cout << "Generated JSON:" << std:: endl; std:: cout << jsonString << std:: endl; Person parsedPerson; json parsedData = json:: parse ( jsonString) ; parsedPerson. name = parsedData[ "name" ] ; parsedPerson. age = parsedData[ "age" ] ; parsedPerson. isStudent = parsedData[ "isStudent" ] ; std:: vector< int > parsedGrades = parsedData[ "grades" ] . get < std:: vector< int >> ( ) ; parsedPerson. address. street = parsedData[ "address" ] [ "street" ] ; parsedPerson. address. city = parsedData[ "address" ] [ "city" ] ; parsedPerson. addresses. clear ( ) ; for ( const auto & addr : parsedData[ "addresses" ] ) { Address parsedAddr; parsedAddr. street = addr[ "street" ] ; parsedAddr. city = addr[ "city" ] ; parsedPerson. addresses. push_back ( parsedAddr) ; } std:: cout << "Name: " << parsedPerson. name << std:: endl; std:: cout << "Age: " << parsedPerson. age << std:: endl; std:: cout << "Is Student: " << parsedPerson. isStudent << std:: endl; std:: cout << "Grades: " ; for ( int grade : parsedPerson. grades) { std:: cout << grade << " " ; } std:: cout << std:: endl; std:: cout << "Address: Street: " << parsedPerson. address. street << ", City: " << parsedPerson. address. city << std:: endl; std:: cout << "Addresses:" << std:: endl; for ( const auto & addr : parsedPerson. addresses) { std:: cout << "Street: " << addr. street << ", City: " << addr. city << std:: endl; } return 0 ;
}