美文网首页
库之 - Json

库之 - Json

作者: googoler | 来源:发表于2020-04-16 16:18 被阅读0次

JAVA Json

  • jackson
  • gson
  • fastjson
    建议使用 jackson

参考:


C#

  • Newtonsoft.Json

C

  • CJson

CPP

  • JsonCpp

简介:

  • JsonCpp是一个 C++ json 库。

  • 所属语言
    C++

  • github

分析

  • C++ json 库

参考:

应用
Json简介

  • 键值对 valuestring:value
        键值之间的对应关系使用:表示,左边的为 \color{red} {name},右边的为\color{red} {value}

Json中仅支持两种结构

  • 对象(object):name->value键值对(pair)的集合
        object可以认为是多个 \color{red} {无序的} pair的集合, 其语法是以" \color{red} { \{ } "作为object开始,以" \color{red} { \} } "作为object结束,不同的pair之间使用" \color{red} { , } "分割;

  • 数组(array): 值的有序表
        array是value的有序集合,其语法是以 \color{red} { [ } 作为array起始,以 \color{red} { ] } 作为array结束,array元素之间使用 \color{red} { , } 分割;

  • stringWrite

#include "json/json.h"
#include <iostream>
/** \brief Write a Value object to a string.
 * Example Usage:
 * $g++ stringWrite.cpp -ljsoncpp -std=c++11 -o stringWrite
 * $./stringWrite
 * {
 *     "action" : "run",
 *     "data" :
 *     {
 *         "number" : 1
 *     }
 * }
 */
int main() {
  Json::Value root;
  Json::Value data;
  constexpr bool shouldUseOldWay = false;   //是否使用旧的解释方式
  root["action"] = "run";
  data["number"] = 1;
  root["data"] = data;

  if (shouldUseOldWay) {
    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    std::cout << json_file << std::endl;
  } else {
    Json::StreamWriterBuilder builder;
    const std::string json_file = Json::writeString(builder, root);
    std::cout << json_file << std::endl;
  }
  return EXIT_SUCCESS;
}


  • streamWrite

#include "json/json.h"
#include <iostream>
/** \brief Write the Value object to a stream.
 * Example Usage:
 * $g++ streamWrite.cpp -ljsoncpp -std=c++11 -o streamWrite
 * $./streamWrite
 * {
 *     "Age" : 20,
 *     "Name" : "robin"
 * }
 */
int main() {
  Json::Value root;
  Json::StreamWriterBuilder builder;
  const std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());

  root["Name"] = "robin";
  root["Age"] = 20;
  writer->write(root, &std::cout);

  return EXIT_SUCCESS;
}


  • readFromString

#include "json/json.h"
#include <iostream>
/**
 * \brief Parse a raw string into Value object using the CharReaderBuilder
 * class, or the legacy Reader class.
 * Example Usage:
 * $g++ readFromString.cpp -ljsoncpp -std=c++11 -o readFromString
 * $./readFromString
 * colin
 * 20
 */
int main() {
  const std::string rawJson = R"({"Age": 20, "Name": "colin"})";
  const int rawJsonLength = static_cast<int>(rawJson.length());
  constexpr bool shouldUseOldWay = false;
  JSONCPP_STRING err;
  Json::Value root;

  if (shouldUseOldWay) {
    Json::Reader reader;
    reader.parse(rawJson, root);
  } else {
    Json::CharReaderBuilder builder;
    const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
    if (!reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root,
                       &err)) {
      std::cout << "error" << std::endl;
      return EXIT_FAILURE;
    }
  }
  const std::string name = root["Name"].asString();
  const int age = root["Age"].asInt();

  std::cout << name << std::endl;
  std::cout << age << std::endl;
  return EXIT_SUCCESS;
}


  • readFromStream

#include "json/json.h"
#include <fstream>
#include <iostream>
/** \brief Parse from stream, collect comments and capture error info.
 * Example Usage:
 * $g++ readFromStream.cpp -ljsoncpp -std=c++11 -o readFromStream
 * $./readFromStream
 * // comment head
 * {
 *    // comment before
 *    "key" : "value"
 * }
 * // comment after
 * // comment tail
 */
int main(int argc, char* argv[]) {
  Json::Value root;
  std::ifstream ifs;
  ifs.open(argv[1]);

  Json::CharReaderBuilder builder;
  builder["collectComments"] = true;
  JSONCPP_STRING errs;
  if (!parseFromStream(builder, ifs, &root, &errs)) {
    std::cout << errs << std::endl;
    return EXIT_FAILURE;
  }
  std::cout << root << std::endl;
  return EXIT_SUCCESS;
}


  • 读取 Json 字符串

std::string rawJson = str;
const int rawJsonLength = static_cast<int>(rawJson.length());
Json::Value root;
Json::CharReaderBuilder builder;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
if (!reader || !reader->parse(rawJson.c_str(), rawJson.c_str() + rawJsonLength, &root, nullptr))
{
    return false;
}


  • Json 对象 转 字符串

Json::Value root;
root["item1"] = "1";
root["item2"] = "2";
std::string request = root.toStyledString();

  • Json 数组

  1. 完整数组:
Json::Value root;
Json::Value items;
items.append(Json::Value("item1"));
items.append(Json::Value("item2"));
root["other"] = "other";
root["items"] = items;

//数组个数
unsigned int count = root["items"].size(); 

//循环数组
for (auto var :  root["items"]) {
    std::string str = var.asString();
}
  1. 关于Json 空数组类型
Json::Value root;
root["other"] = "other";
root["items"]..resize(0);

  • 示例:

    Json::Value root;
    root["fileName"] = "fileName";
    root["parentId"] = u8R"(parentId)";     //C++ 11 新语法
    root["remark"] = u8"";                  //C++ 11 新语法
    Json::Value items;
    {
        Json::Value item;
        item["orgType"] = 2;
        item["userId"] = "userId";
        item["authorizeList"].append(Json::Value("4"));
        items.append(item);
    }
    root["userAuthorizeList"] = items;

    string reqData = root.toStyledString();

reqData 的Json字符串为:


reqData

相关文章

  • 库之 - Json

    JAVA Json jackson gson fastjson建议使用 jackson 参考: Java操作JSO...

  • Swift常用第三方框架搜集

    框架列表: 网络库: Alamofire JSON解析库: SwiftJSON JSON to Model:Obj...

  • json loads和dumps

    JSON 函数 使用 JSON 函数需要导入 json 库:import json。 json.dumps将 Py...

  • Android下json-c库使用

    json-c库 json-c 库中是在嵌入式开发中常用的库。 因为很多地方都以json数据数据交互协议, 尤其嵌入...

  • Go语言标准库之JSON编解码

    Go语言标准库之JSON编解码 基本的类型 Go语言中的数据类型和JSON的数据类型的关系 bool -> JSO...

  • Go语言标准库之JSON编解码

    Go语言标准库之JSON编解码 基本的类型 Go语言中的数据类型和JSON的数据类型的关系 bool -> JSO...

  • java json 库之 jackson

    jackson 是一个 java json 库,提供了完备的 json 解析,序列化以及反序列化功能 依赖配置 在...

  • 2018-02-07 数据库导数据命令

    导出数据库到db_bak.json 导入db.json到数据库

  • test

    载入json库 import json 封装 读取学生信息数据库 def stu_massage_list():w...

  • JSON库

    JSON库将json对象或节点转换成字典、将json数组转换成列表、将json字符串转换成python字符串,tr...

网友评论

      本文标题:库之 - Json

      本文链接:https://www.haomeiwen.com/subject/iwzrvhtx.html