Jsoncpp 使用方法大全

Json(JavaScript Object Notation )是一种轻量级的数据交换格式。简而言之,Json组织形式就和python中的字典, C/C++中的map一样,是通过key-value对来组织的,key是任意一个唯一字符串,value可以是bool,int,string 或者嵌套的一个json。关于Json 格式可以参考官方网站。 
Jsoncpp 是一个用来处理 Json文本的开源C++库,下面就简单介绍使用Jsoncpp对Json文件的常见操作。


Jsoncpp 常用变量介绍

在Jsoncpp中,有几个常用的变量特别重要,首先介绍一下。

Json::Value

Json::Value 用来表示Json中的任何一种value抽象数据类型,具体来说,Json中的value可以是一下数据类型:

  • 有符号整数 signed integer [range: Value::minInt - Value::maxInt]
  • 无符号整数 unsigned integer (range: 0 - Value::maxUInt)
  • 双精度浮点数 double
  • 字符串 UTF-8 string
  • 布尔型 boolean
  • 空 ‘null’
  • 一个Value的有序列表 an ordered list of Value
  • collection of name/value pairs (javascript object)

可以通过 [] 的方法来取值。

//Examples:
Json::Value null_value; // null
Json::Value arr_value(Json::arrayValue); // []
Json::Value obj_value(Json::objectValue); // {}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5

Json::Reader

Json::Reader可以通过对Json源目标进行解析,得到一个解析好了的Json::Value,通常字符串或者文件输入流可以作为源目标。

假设现在有一个example.json文件

{
    "encoding" : "UTF-8",
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],
    "indent" : { "length" : 3, "use_space": true }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

使用Json::Reader对Json文件进行解析:

bool parse (const std::string &document, Value &root, bool collectComments=true)
bool parse (std::istream &is, Value &root, bool collectComments=true)
 
 
  • 1
  • 2

Json::Value root;
Json::Reader reader;
std::ifstream ifs("example.json");//open file example.json

if(!reader.parse(ifs, root)){
   // fail to parse
}
else{
   // success
   std::cout<<root["encoding"].asString()<<endl;
   std::cout<<root["indent"]["length"].asInt()<<endl;
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

使用Json::Reader对字符串进行解析

bool Json::Reader::parse ( const char * beginDoc,
        const char * endDoc,
        Value & root,
        bool collectComments = true 
    )   
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  Json::Value root;
  Json::Reader reader;
  const char* s = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}"; 
  if(!reader.parse(s, root)){
    // "parse fail";
  }
  else{
      std::cout << root["uploadid"].asString();//print "UP000000"
  }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Json::Writer

Json::Writer 和 Json::Reader相反,是把Json::Value对象写到string对象中,而且Json::Writer是个抽象类,被两个子类Json::FastWriter和Json::StyledWriter继承。 
简单来说FastWriter就是无格式的写入,这样的Json看起来很乱没有格式,而StyledWriter就是带有格式的写入,看起来会比较友好。

Json::Value root;
Json::Reader reader;
Json::FastWriter fwriter;
Json::StyledWriter swriter;

if(! reader.parse("example.json", root)){
// parse fail
    return 0;
}
std::string str = fwriter(root);
std::ofstream ofs("example_fast_writer.json");
ofs << str;
ofs.close();

str = swriter(root);
ofs.open("example_styled_writer.json");
ofs << str;
ofs.close();

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

结果: 
example_styled_writer.json

{
    "encoding" : "UTF-8",
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],
    "indent" : { "length" : 3, "use_space": true }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

example_fast_writer.json

{"encoding" : "UTF-8","plug-ins" : ["python","c++","ruby"],"indent" : { "length" : 3, "use_space": true}}
 
 
  • 1

Jsoncpp 其他操作

通过前面介绍的Json::value, Json::Reader, Json::Reader 可以实现对Json文件的基本操作,下面介绍一些其他的常用的操作。

判断key是否存在

bool Json::Value::isMember ( const char * key) const

Return true if the object has a member named key.

Note
    'key' must be null-terminated. 

bool Json::Value::isMember ( const std::string &  key) const
bool Json::Value::isMember ( const char* key, const char * end ) const

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
// print "encoding is a member"
if(root.isMember("encoding")){
    std::cout<<"encoding is a member"<<std::endl;
}
else{
    std::cout<<"encoding is not a member"<<std::endl;
}

// print "encode is not a member"
if(root.isMember("encode")){
    std::cout<<"encode is a member"<<std::endl;
}
else{
    std::cout<<"encode is not a member"<<std::endl;
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

判断Value是否为null

首先要给example.json添加一个key-value对:

{
    "encoding" : "UTF-8",
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
    ],
    "indent" : { "length" : 3, "use_space": true },
    "tab-length":[],
    "tab":null
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

判断是否为null的成员函数

bool Json::Value::isNull ( ) const
 
 
  • 1
if(root["tab"].isNull()){
    std::cout << "isNull" <<std::endl;//print isNull
}
 
 
  • 1
  • 2
  • 3
if(root.isMember("tab-length")){//true
    if(root["tab-length"].isNull()){
      std::cout << "isNull" << std::endl;
    }
    else std::cout << "not Null"<<std::endl;
    // print "not Null", there is a array object([]), through this array object is empty
    std::cout << "empty: " << root["tab-length"].empty() << std::endl;//print empty: 1
    std::cout << "size: " << root["tab-length"].size() << std::endl;//print size: 0
  }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

另外值得强调的是,Json::Value和C++中的map有一个共同的特点,就是当你尝试访问一个不存在的 key 时,会自动生成这样一个key-value默认为null的值对。也就是说

 root["anything-not-exist"].isNull(); //false
 root.isMember("anything-not-exist"); //true
 
 
  • 1
  • 2

总结就是要判断是否含有key,使用isMember成员函数,value是否为null使用isNull成员函数,value是否为空可以用empty() 和 size()成员函数。

得到所有的key

typedef std::vector<std::string> Json::Value::Members

Value::Members Json::Value::getMemberNames ( ) const

Return a list of the member names.

If null, return an empty list.

Precondition
    type() is objectValue or nullValue 

Postcondition
    if type() was nullValue, it remains nullValue 


 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

可以看到Json::Value::Members实际上就是一个值为string的vector,通过getMemberNames得到所有的key。

删除成员

Value Json::Value::removeMember( const char* key)   

Remove and return the named member.
Do nothing if it did not exist.

Returns
    the removed Value, or null. 

Precondition
    type() is objectValue or nullValue 

Postcondition
    type() is unchanged 

Value Json::Value::removeMember( const std::string & key)   

bool Json::Value::removeMember( std::string const &key, Value *removed)         

Remove the named map member.
Update 'removed' iff removed.

Parameters
    key may contain embedded nulls.

Returns
    true iff removed (no exceptions) 


 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

参考

http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: C++和MFC结合使用JsonCpp库可以很方便地处理JSON数据。JsonCpp是开源的C++库,提供了用于读取、写入和操作JSON数据的方法和类。 首先,使用JsonCpp库,我们需要将JsonCpp的头文件和源文件包含到项目中,并链接相应的库文件。 然后,我们可以使用JsonCpp库提供的方法来解析和生成JSON数据。例如,如果我们有一个JSON字符串,我们可以使用Json::Reader类来解析它: ``` Json::Value root; Json::Reader reader; std::string jsonString = "{\"name\":\"John\",\"age\":30}"; // 假设我们有一个JSON字符串 bool parsingSuccess = reader.parse(jsonString, root); if (parsingSuccess) { std::string name = root["name"].asString(); // 获取"name"字段的值 int age = root["age"].asInt(); // 获取"age"字段的值 // 进一步处理... } ``` 同样,如果我们想生成一个JSON字符串,我们可以使用Json::Value类来构建JSON对象: ``` Json::Value root; root["name"] = "John"; root["age"] = 30; // 进一步添加其他字段... Json::FastWriter writer; std::string jsonString = writer.write(root); // 输出结果:{"name":"John","age":30} ``` 除了读取和生成JSON数据之外,JsonCpp还提供了其他一些功能,如检查JSON数据是否有效、遍历JSON对象等。 总之,C++和MFC结合使用JsonCpp库可以方便地处理JSON数据。我们可以使用JsonCpp提供的方法来解析和生成JSON数据,从而实现对JSON数据的读取和操作。 ### 回答2: 在C++/MFC中使用JSONcpp库可以方便地进行JSON数据的解析和生成。JSONcpp是一个开源的C++库,提供了一套API供开发人员操作JSON数据。 首先,在使用JSONcpp之前,需要将其库文件添加到项目中。可以从JSONcpp的官方网站或其他途径下载JSONcpp的源代码,并将其编译为静态库或动态库文件。 接下来,可以通过以下步骤在C++/MFC中使用JSONcpp: 1. 引入JSONcpp的头文件: ```cpp #include <json/json.h> ``` 2. 创建一个Json::Value对象,用于存储解析后的JSON数据或将数据转换为JSON格式: ```cpp Json::Value jsonValue; ``` 3. 解析JSON数据: ```cpp Json::CharReaderBuilder jsonBuilder; std::string jsonStr = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"; std::istringstream jsonStream(jsonStr); std::string jsonErrs; if (Json::parseFromStream(jsonBuilder, jsonStream, &jsonValue, &jsonErrs)) { // 解析成功,可以通过jsonValue对象访问解析后的数据 } else { // 解析失败,处理错误 } ``` 4. 访问解析后的JSON数据: ```cpp std::string name = jsonValue["name"].asString(); int age = jsonValue["age"].asInt(); std::string city = jsonValue["city"].asString(); ``` 5. 生成JSON数据: ```cpp jsonValue["name"] = "John"; jsonValue["age"] = 30; jsonValue["city"] = "New York"; std::ostringstream jsonStream; Json::StreamWriterBuilder jsonWriter; std::unique_ptr<Json::StreamWriter> writer(jsonWriter.newStreamWriter()); writer->write(jsonValue, &jsonStream); std::string jsonStr = jsonStream.str(); ``` 通过以上步骤,可以在C++/MFC中很方便地使用JSONcpp进行JSON数据的解析和生成。在实际应用中,可以根据需要,结合其他功能,灵活地处理JSON数据。 ### 回答3: 在使用MFC开发项目时,我们可以通过Jsoncpp库来处理JSON数据。Jsoncpp是一个开源的C++库,提供了一套简单易用的API来读取、解析、生成和操作JSON数据。 首先,我们需要将Jsoncpp库添加到MFC项目中。可以从官方网站上下载到源代码,然后将其编译成静态链接库或动态链接库,再将其导入到MFC项目中。 接下来,我们可以使用Jsoncpp提供的API来解析JSON数据。可以使用Json::Value对象来表示JSON数据,并通过Json::Reader来读取JSON数据并解析成Json::Value对象。例如,可以使用以下代码来解析一个包含JSON数据的字符串: ```cpp #include <json/json.h> #include <iostream> int main() { std::string jsonData = "{\"name\":\"John\",\"age\":30}"; Json::Value root; Json::Reader reader; bool success = reader.parse(jsonData, root); if (success) { std::string name = root["name"].asString(); int age = root["age"].asInt(); std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; } else { std::cout << "Failed to parse JSON!" << std::endl; } return 0; } ``` 上述代码将会输出以下结果: ``` Name: John Age: 30 ``` 除了解析JSON数据,我们还可以使用Jsoncpp生成JSON数据。可以使用Json::Value对象来表示生成的JSON数据,并通过Json::FastWriter或Json::StyledWriter来将Json::Value对象转换为字符串。例如,可以使用以下代码来生成一个包含JSON数据的字符串: ```cpp #include <json/json.h> #include <iostream> int main() { Json::Value root; root["name"] = "John"; root["age"] = 30; Json::FastWriter writer; std::string jsonData = writer.write(root); std::cout << "JSON Data: " << jsonData << std::endl; return 0; } ``` 上述代码将会输出以下结果: ``` JSON Data: {"name":"John","age":30} ``` 除了解析和生成JSON数据,Jsoncpp还提供了其他一些API来操作JSON数据,例如增加、修改、删除和查找JSON对象和数组中的元素。 总之,使用Jsoncpp库可以很方便地在MFC项目中处理JSON数据。无论是解析JSON数据还是生成JSON数据,Jsoncpp都提供了简单易用的API来满足我们的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值