zoukankan      html  css  js  c++  java
  • 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"
        }
      ]
    }
    */
    
  • 相关阅读:
    JZOJ 5870 地图
    20190921
    20190919
    SP703 SERVICE
    UVA323 Jury Compromise
    [note]一类位运算求最值问题
    [BZOJ3674]可持久化并查集
    [luogu3359]改造异或树
    [luogu4755]Beautiful Pair
    [BJWC2012]冻结
  • 原文地址:https://www.cnblogs.com/zwvista/p/9591853.html
Copyright © 2011-2022 走看看