JSON數據的解析和生成(C++)


課題

  • 將 JSON 字符串反序列化為 Persons 類(結構)的對象 ,然后將這個對象序列化為 JSON 字符串。
  • Persons 類(結構)包含一個字段:Person 類(結構)的 persons 數組。
  • Person 類(結構)包含兩個字段:字符串類型的 name 字段和整數類型的 age 字段。

安裝 "JSON for Modern C++"

$ brew tap nlohmann/json
$ brew install nlohmann_json

安裝之后將/usr/local/Cellar/nlohmann_json/3.1.2/include加入 include

示例

#include <iostream>
#include <nlohmann/json.hpp>
using nlohmann::json;
using namespace std;

struct Person {
    string name;
    int age;
};
struct Persons {
    vector<Person> persons;
};
void to_json(json& j, const Person& p) {
    j = json{{"name", p.name}, {"age", p.age}};
}
void from_json(const json& j, Person& p) {
    p.name = j.at("name").get<string>();
    p.age = j.at("age").get<int>();
}
void to_json(json& j, const Persons& ps) {
    j = json{{"persons", ps.persons}};
}
void from_json(const json& j, Persons& ps) {
    ps.persons = j.at("persons").get<vector<Person>>();
}

string jsonString = R"({
  "persons" : [
    {
      "name" : "Joe",
      "age" : 12
    }
  ]
})";

int main(int argc, char *args[])
{
    json j = json::parse(jsonString);
    Persons ps = j;
    auto &p = ps.persons[0];
    cout << "name: " << p.name << endl
        << "age: " << p.age << endl;
    j = ps;
    cout << j << endl;
    cout << j.dump(2) << endl;

    return 0;
}

/*
name: Joe
age: 12
{"persons":[{"age":12,"name":"Joe"}]}
{
  "persons": [
    {
      "age": 12,
      "name": "Joe"
    }
  ]
}
*/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM