LN : JSON (利用C++實現JSON)

来源:http://www.cnblogs.com/renleimlj/archive/2016/05/25/5525591.html
-Advertisement-
Play Games

Appreciation to our TA, 王毅峰, who designed this task. 問題描述 JSON, JavaScript Object Notation,is an flexible format that uses human readable text to tran ...


  • Appreciation to our TA, 王毅峰, who designed this task.

問題描述

JSON, JavaScript Object Notation,is an flexible format that uses human-readable text to transmit data objects consisting of key-value pairs(鍵值對)
To construct a json object, we need to parse a raw string

For example

// {"name":"lilei","country":"china","age":"20"}
// in constructor, we parse the string to map
// that is, we find the first key "name", and correspoding value "lilei"
// then we modify our private data member map<string, string> _data
// _data["name"] = "lilei"
// don't stop until all the key-value pairs are stored in _data
json test("{\"name\":\"lilei\",\"country\":\"china\",\"age\":\"20\"}");

NOTE:

To simplify the problem

  1. You just need to finish the constructor,which find out the key/value pairs and store in _data
  2. all the string doesn't consist of space(空格), and it is strictly formed like {"key1":"value1","key2":"value2","key3":"value3"}
  3. all the key and value have double quotation marks(雙引號)
  4. in front of them and after them(所有鍵的前後和值的前後都有雙引號)
  5. read json.h and main.cpp for more details

問題解析

問題的關鍵是如何從一個長字元串中獲取對應的鍵值對,並且運用make_pair組成一組map。

json.h

#ifndef JSON_H
#define JSON_H
#include <iostream>
#include <string>
#include <map>

using std::ostream;
using std::string;
using std::map;

class json {
private:
    // store the relationship between key and value
    map<string, string> _data;
public:
    // parse the raw string to map<string, string>
    explicit json(string);

    // return mutable value according to key
    string& operator[](string key) {
        return _data[key];
    }

    // return the number of key/value
    int count() const {
        return _data.size();
    }

    // output
    friend ostream& operator<<(ostream& os, const json& obj) {
        map<string, string>::iterator it;
        map<string, string> data = obj._data;
        int num = 0;
        os << "{\n";
        for (it = data.begin(); it != data.end(); it++) {
            num++;
            os << "    \"" << it->first << "\": \"" << it->second << "\"";
            if (num != obj.count()) {
                os << ",";
            }
            os << "\n";
        }
        os << "}";
        return os;
    }
};
#endif  // JSON_H

json.cpp

#include "json.h"
using namespace std;

json::json(string a) {
    int len = a.length();
    string m, n;
    int famen = 0;
    for (int i = 0; i < len; i++) {
        if (a[i] == '"') {
            famen++;
            continue;
        }
        if (famen%4 == 1) {
            m.push_back(a[i]);
        } else if (famen%4 == 3) {
            n.push_back(a[i]);
        } else if (famen%4 == 0 && famen != 0) {
            _data.insert(make_pair(m, n));
            m.clear();
            n.clear();
        }
    }
}

main.cpp

#include <iostream>
#include <string>
#include "json.h"

using std::cin;
using std::string;
using std::cout;
using std::endl;

int main(void) {
    {
        // {"name":"lilei","country":"china","age":"20"}
        json test("{\"name\":\"lilei\",\"country\":\"china\",\"age\":\"20\"}");
        cout << test << endl;
        test["name"] = "mike";
        test["country"] = "USA";
        cout << test << endl;
    }
    {
        // {"book_name":"c++ primer 5th","price":"$19.99"}
        json test("{\"book_name\":\"c++ primer 5th\",\"price\":\"$19.99\"}");
        cout << test << endl;
        test["page"] = "345";
        test["ISBN"] = "978-962";
        cout << test << endl;
    }
    {
        int AvoidRepeatedData;
        cin >> AvoidRepeatedData;
        string rawString;
        cin >> rawString;
        json test(rawString);
        cout << test << endl;
    }
    return 0;
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 概述 GenEvent 是事件處理的通用部分的抽象。 通過 GenEvent ,我們給已有的服務 動態 的添加 事件處理。 GenEevent 和 GenServer 的區別 之前已經介紹了 GenServer ,GenServer 和 GenEvent 的主要區別在於: GenServer 是服務 ...
  • WIN 下的超動態菜單(一)簡介 WIN 下的超動態菜單(二)用法 作者:黃山松,發表於博客園:http://www.cnblogs.com/tomview/ auto_dynamenu 是一個動態生成WINDOWS菜單的c++封裝庫,設計思路是要儘量簡化動態菜單的生成代碼,在程式界面任何地方想要顯... ...
  • 這個模塊提供了與 Perl 相似l的正則表達式匹配操作。Unicode字元串也同樣適用。 正則表達式使用反斜杠" \ "來代表特殊形式或用作轉義字元,這裡跟Python的語法衝突,因此,Python用" \\\\ "表示正則表達式中的" \ ",因為正則表達式中如果要匹配" \ ",需要用\來轉義, ...
  • ...
  • 我相信很多人對構造函數在什麼時候產生,以及產生的原因,理解得不是很透徹;更有甚者認為預設構造函數和複製構造函數是一定會產生的,成員變數就應該在初始化參數列表中進行初始化,當然這些是初學者的認識,下麵分享一下我的看法。 構造函數不負責分配記憶體,只是在分配好的一塊記憶體中進行賦值操作.這一點我們可以很容易 ...
  • 繼承 指的是一個類(稱為子類、子介面)繼承另外的一個類(稱為父類、父介面)的功能,並可以增加它自己的新功能的能力,繼承是類與類或者介面與介面之間最常見的關係;在Java中此類關係通過關鍵字extends明確標識,在設計時一般沒有爭議性; 實現 指的是一個class類實現interface介面(可以是 ...
  • 摘要:Python語言的特點 >優雅、明確、簡單 一、Python適合的領域 web網站和各種網路服務 系統工具和腳本 作為“膠水”語言,把其他語言開發的模塊包裝起來方便使用 二、Python不適合的領域 貼近硬體的代碼(首選C) 移動開發:ios/Android有各自的開發語言(Objc,Swif ...
  • 主要介紹spring mvc控制框架的流程及原理 Spring Web MVC處理請求的流程 具體執行步驟如下: 首先用戶發送請求————>前端控制器,前端控制器根據請求信息(如URL)來決定選擇哪一個頁面控制器進行處理並把請求委托給它,即以前的控制器的控制邏輯部分;圖2-1中的1、2步驟; 頁面控 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...