Poco C++——JSON解析


#include <iostream>
#include "Poco/Dynamic/Var.h"
#include "Poco/Dynamic/Pair.h"
#include "Poco/Dynamic/VarIterator.h"
#include "Poco/JSON/Array.h"
#include <vector>
#include <map>
#include "Poco/JSON/Parser.h"

using Poco::Dynamic::Var;
using Poco::JSON::Parser;
using Poco::Dynamic::Pair;
using Poco::JSON::Array;
using Poco::JSON::Object;

int main(int argc, const char * argv[]) {
    using namespace std;
    Poco::JSON::Object scores;
    scores.set("數學", 98);
    scores.set("英語", 99);
    scores.set("語文", 89);
    scores.set("化學", 100);
    scores.set("物理", 98);
    scores.set("生物", 96);
    Poco::JSON::Object student;
    student.set("name", "小南");
    student.set("address", "四川省成都市錦江區錦華路一段7號愛家麗苑1棟1單元305室");
    student.set("class", "四川省成都市第七中學2010級2班");
    student.set("grade", Poco::Dynamic::Var(scores));
    Poco::Dynamic::Var JSON(student);
    cout << JSON.toString() << endl;
    string theJSON = JSON.toString();
    Poco::JSON::Parser parser;
    Poco::Dynamic::Var json = parser.parse(theJSON);
    Poco::JSON::Object theObj = *json.extract<Poco::JSON::Object::Ptr>();
    Poco::Dynamic::Var theScores = theObj.get("grade");
    Poco::Dynamic::Var name = theObj.get("name");
    Poco::Dynamic::Var address = theObj.get("address");
    Poco::Dynamic::Var theClass = theObj.get("class");
    Poco::JSON::Object grade = *theScores.extract<Poco::JSON::Object::Ptr>();
    Poco::Dynamic::Var math = grade.get("數學");
    Poco::Dynamic::Var english = grade.get("英語");
    Poco::Dynamic::Var chinese = grade.get("語文");
    Poco::Dynamic::Var wuli = grade.get("物理");
    Poco::Dynamic::Var shengwu = grade.get("生物");
    Poco::Dynamic::Var huaxue = grade.get("化學");
    cout << "\n\n姓名: " << name.toString() << endl
         << "班級: " << theClass.toString() << endl
         << "地址: " << address.toString() << endl
         << "數學: " << math.convert<int>() << endl
         << "語文: " << chinese.convert<int>() << endl
         << "化學: " << huaxue.convert<int>() << endl
         << "物理: " << wuli.convert<int>() << endl
    << "生物: " << shengwu.convert<int>() << endl;
    return 0;
}

輸出結果:
{
  "address" : "四川省成都市錦江區錦華路一段7號愛家麗苑1棟1單元305室",
  "class" : "四川省成都市第七中學2010級2班",
  "grade" : {
    "化學" : 100,
    "數學" : 98,
    "物理" : 98,
    "生物" : 96,
    "英語" : 99,
    "語文" : 89
  },
  "name" : "小南"
}


姓名: 小南
班級: 四川省宣漢中學2010級2班
地址: 四川省成都市錦江區錦華路一段7號愛家麗苑1棟1單元305室
數學: 98
語文: 89
化學: 100
物理: 98
生物: 96

 


免責聲明!

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



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