JsonCpp——json文件的解析

定义:

  官网: http://json.org/
  在线解析器:http://json.cn/ http://www.bejson.com/
  JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它使得人们很容易的进行阅读和编写。同时也方便了机器进行解析和生成。它是基于 JavaScript Programming Language , Standard ECMA-262 3rd Edition - December 1999 的一个子集。 JSON 采用完全独
立于程序语言的文本格式,但是也使用了类 语言的习惯(包括 C, C++, C#, Java, JavaScript,Perl, Python 等)。这些特性使 JSON 成为理想的数据交换语言。 


解释格式:

一个json实例

{ 
  "animals": {
            "dog": [
                        {"name": "Rufus", "age": 15},
                        {"name": "Marty","age": null}
                      ],
            "cat": [
                        {"name": "bosi","age": 15},
                        {"name": "maowang","age": null}
                    ]
               }
}                                    

 

文档结构分析:

  json 简单说就是 javascript 中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。

1)对象(Object)
  对象在 js 中表示为“{}”括起来的内容, 数据结构为 {keyvalue,keyvalue,...}的键值对的结构, 在面向对象的语言中, key 为对象的属性, value 为对应的属性值, 所以很容易理解, 取值方法为 对象.key 获取属性值, 这个属性值的类型可以是 数字、字符串、 数组、 对象几种。
 


2)数组(Array)

  数组在 js 中是中括号“[]”括起来的内容, 数据结构为 ["java","javascript","vb",...],取值方式和所有语言中一样, 使用索引获取, 字段值的类型可以是 数字、 字符串、数组、 对象几种。 



3)数据类型

  • 值(value)

  值( value) 可以是双引号括起来的字符串( string) 、 数值(number)truefalse、null、 对象( object) 或者数组( array) 。 这些结构可以嵌套。 


    eg:“abc”, { “abc”:123} [1,2,3] true false null

  • 字符串:

  字符串( string) 是由双引号包围的任意数量 Unicode 字符的集合, 使用反斜线转义。 一个字符( character) 即一个单独的字符串( character string) 。 

  eg:“abc” “\r\n” “u00A9”

  • 数值

  数值( number) 也与 C 或者 Java 的数值非常相似。 只是 JSON 的数值没有使用八进制与十六进制格式。 

  eg:123 -123 1.234e5

 

 

 

JsonCpp

简介
JSON is a lightweight data-interchange format. It can represent numbers,strings, ordered sequences of values, and collections of name/value pairs.JsonCpp is a C++ library that allows manipulating JSON values, including serialization and deserialization to and from strings. It can also preserve existingstore user input files. 




JsonCpp环境搭建:

下载地址:

https://github.com/open-source-parsers/jsoncpp#generating-amalgamated-source-and-header

Qt JsonCpp 安装
① 解压 jsoncpp-master.zip
② 在根目录下, 运行 python amalgamate.py
③ 在根目录中生成 dist 文件夹包含三个文件 dist/json/json-forwards.h
dist/json/json.h dist/json.cpp
④ 在 Qt 工程目录下, 生成 json 文件夹, 并拷贝 json 目录下。
⑤ 在 Qt 工程中添加现有文件即可。

 

JSon 框架
Json::Value jsoncpp 中最基本、最重要的类,用于表示各种类型的对象。
Json::Reader 用来将内存或文件中的 json 数据转换成 Json::Value 类型。
Json::Writer 用来将 Json::Value 类型转换成内存或文件中的 json 数据。



读写 Json
1)写:

#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace Json;
using namespace std;
#if 0
{ 
  "animals": {
            "dog": [
                        {"name": "Rufus", "age": 15},
                        {"name": "Marty","age": null}
                      ],
            "cat": [
                        {"name": "bosi","age": 15},
                        {"name": "maowang","age": null}
                    ]
               }
}              

#endif


void writeTestJson()
{
  //对象的创建
  Value map;
  map["key1"] = 1;
  map["key2"] = "1";
  map["key3"] ;
  //数组的创建
  Value arr;
  Value item;
  for(int i=0; i<10; i++)
  {
    item["key"] = 1;
    item["key2"] = 2;
    arr.append(item);
  } 
  string str
= arr.toStyledString();   cout<<str; }

void writeJson() {   Value dogArr;   Value Item;   Item[
"name"] = "Rufus";Item["age"] = 15;   dogArr.append(Item);   Item["name"] = "Marty";Item["age"];   dogArr.append(Item);   Value catArr;   Item["name"] = "bosi";Item["age"] = 15;   catArr.append(Item);   Item["name"] = "maowang";Item["age"];   catArr.append(Item);   Value rootValue;   rootValue["dog"] = dogArr;   rootValue["cat"] = catArr;   Value root;   root["anmials"] = rootValue;   string str = root.toStyledString();   cout<<str;   ofstream ofs("animal.json");   ofs<<str;   ofs.close(); }

int main() {   writeJson();   
return 0; }

 

2)读

void readJson()
{
  ifstream ifs("animal.json");
  if(!ifs)
  cout<<"open error"<<endl;
  Value root;
  Reader reader;
  if(reader.parse(ifs,root))
  {
    cout<<root.toStyledString()<<endl;
    Value &arr = root["animals"]["dog"];
    for(int i=0; i<arr.size(); i++)
    {
      cout<<"name"<<arr[i]["name"]<<endl;
      cout<<"age "<<arr[i]["age"]<<endl;
    }
    arr
= root["animals"]["cat"];     for(int i=0; i<arr.size(); i++)     {       cout<<"name"<<arr[i]["name"]<<endl;       cout<<"age "<<arr[i]["age"]<<endl;     }   } }

3)改

void readWriteJson()
{
  ifstream ifs("animal.json");
  if(!ifs)
  cout<<"open error"<<endl;
  Value root;
  Reader reader;
  if(reader.parse(ifs,root))
  {
    cout<<root.toStyledString()<<endl;
    Value &arr = root["animals"]["dog"];
    root["person"];
    root["animals"]["tiger"];
    root["animals"].removeMember("dog");
    cout<<root.toStyledString()<<endl;
    root.removeMember("animals");
    cout<<root.toStyledString()<<endl;
  }
}


int main() {   readWriteJson();   
return 0; }

 

posted @ 2018-07-08 13:06  小念之歌  阅读(925)  评论(0编辑  收藏  举报