C++ jsoncpp结构体数据转换为json字符串 // json字符串转换为结构体数据

// jsoncpp使用方法总结
// 结构体数据转换为json字符串
// json字符串转换为结构体数据

 

// jsoncpp下载地址 http://sourceforge.net/projects/jsoncpp/

 

// 样例代码如下

#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <exception>
#include <string>
#include "json/json.h"
 
// 测试使用的结构体
typedef struct {
    int nNum;
    char szFile[20];
}TEST_ST_FILE;
 
typedef struct {
    char szMemo[20];
    int nCount;
    TEST_ST_FILE szFileList[5];
}TEST_ST_FILE_LIST;
 
// 结构体数据转换为JSON字符串
int StructDataToJsonString(TEST_ST_FILE_LIST *pStructData, char *pJsonData);
// JSON字符串转换为结构体数据
int JsonStringToStructData(char *pJsonData, TEST_ST_FILE_LIST *pStructData);
 
// 主函数
int main(int argc, char *argv[])
{
    TEST_ST_FILE_LIST stFileList;
    char szJsonData[4096];
 
    memset(&stFileList, 0, sizeof(TEST_ST_FILE_LIST));
    memset(szJsonData, 0, sizeof(szJsonData));
 
    // 测试数据
    strncpy(stFileList.szMemo, "jsoncppmemo", sizeof(stFileList.szMemo));
    stFileList.nCount = 5;
    for(int i = 0; i < stFileList.nCount; i++)
    {
        stFileList.szFileList[i].nNum = i + 1;
        sprintf(stFileList.szFileList[i].szFile, "file%d", i + 1);
    }
    printf("struct data to json string.\n");
    printf("memo:%s count:%d.\n", stFileList.szMemo, stFileList.nCount);
    for(int i = 0; i < stFileList.nCount; i++)
    {
        printf("num:%d file:%s.\n", stFileList.szFileList[i].nNum, 
            stFileList.szFileList[i].szFile);
    }
 
    // 结构体数据转换为JSON字符串
    StructDataToJsonString(&stFileList, szJsonData);
    printf("json string:%s.\n", szJsonData);
 
    // JSON字符串转换为结构体数据
    memset(&stFileList, 0, sizeof(TEST_ST_FILE_LIST));
    JsonStringToStructData(szJsonData, &stFileList);
    printf("json string to struct data.\n");
    printf("memo:%s count:%d.\n", stFileList.szMemo, stFileList.nCount);
    for(int i = 0; i < stFileList.nCount; i++)
    {
        printf("num:%d file:%s.\n", stFileList.szFileList[i].nNum, 
            stFileList.szFileList[i].szFile);
    }
    return 0;
}
 
// 结构体数据转换为JSON字符串
int StructDataToJsonString(TEST_ST_FILE_LIST *pStructData, char *pJsonData)
{
    try
    {
        Json::Value root;
        Json::Value arrayObj;
        Json::Value item;
 
        root["memo"] = pStructData->szMemo;
        root["file_count"] = pStructData->nCount;
        // 生成file_list数组
        for(int i = 0; i < pStructData->nCount; i ++)
        {
            item["num"] = pStructData->szFileList[i].nNum;
            item["file"] = pStructData->szFileList[i].szFile;
            arrayObj.append(item);
        }
        root["file_list"] = arrayObj;
        // JSON转换为JSON字符串(已格式化)
        std::string strOut = root.toStyledString();
        //  JSON转换为JSON字符串(未格式化)
        //Json::FastWriter writer;
        //std::string strOut = writer.write(root);
 
        strcpy(pJsonData, strOut.c_str());
    }
    catch(std::exception &ex)
    {
        printf("StructDataToJsonString exception %s.\n", ex.what());
        return -1;
    }
    return 0;
}
 
// JSON字符串转换为结构体数据
int JsonStringToStructData(char *pJsonData, TEST_ST_FILE_LIST *pStructData)
{
    try
    {
        bool bRet = false;
        std::string strTemp;
        Json::Reader reader;
        Json::Value value;
        Json::Value arrayObj;
        Json::Value item;
 
        // JSON字符串转换为JSON数据
        bRet = reader.parse(pJsonData, value);
        if(bRet == false)
        {
            printf("JsonStringToStructData reader parse error.\n");
            return -1;
        }
        // memo
        bRet = value["memo"].empty();
        if(bRet == true)
        {
            printf("JsonStringToStructData memo is not exist.\n");
            return -1;
        }
        strTemp = value["memo"].asString();
        strncpy(pStructData->szMemo, strTemp.c_str(), sizeof(pStructData->szMemo));
        // file_count
        bRet = value["file_count"].empty();
        if(bRet == true)
        {
            printf("JsonStringToStructData file_count is not exist.\n");
            return -1;
        }
        pStructData->nCount = value["file_count"].asInt();
 
        // 解析file_list数组
        arrayObj = value["file_list"];
        pStructData->nCount = arrayObj.size();
        for(int nIdx = 0; nIdx < pStructData->nCount; nIdx++)
        {
            item = arrayObj[nIdx];
            // num
            pStructData->szFileList[nIdx].nNum = item["num"].asInt();
            // file
            strTemp = item["file"].asString();
            strncpy(pStructData->szFileList[nIdx].szFile, strTemp.c_str(), 
                sizeof(pStructData->szFileList[nIdx].szFile));
        }
    }
    catch(std::exception &ex)
    {
        printf( "JsonStringToStructData exception %s.\n", ex.what());
        return -1;
    }
    return 0;
}

 

执行结果
struct data to json string.
memo:jsoncppmemo count:5.
num:1 file:file1.
num:2 file:file2.
num:3 file:file3.
num:4 file:file4.
num:5 file:file5.

json string:{
 "file_count" : 5,
 "file_list" : [
 {
  "file" : "file1",
  "num" : 1
 },
 {
  "file" : "file2",
  "num" : 2
 },
 {
  "file" : "file3",
  "num" : 3
 },
 {
  "file" : "file4",
  "num" : 4
 },
 {
  "file" : "file5",
  "num" : 5
 }
 ],
 "memo" : "jsoncppmemo"
}
.

json string to struct data.
memo:jsoncppmemo count:5.
num:1 file:file1.
num:2 file:file2.
num:3 file:file3.
num:4 file:file4.
num:5 file:file5.
--------------------- 
作者:特招 
来源:CSDN 
原文:https://blog.csdn.net/dgyanyong/article/details/16985235 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
要将MFC结构体数据转换JSON字符串,你可以使用JsonCpp库。以下是一个示例代码,展示了如何将MFC结构体数据转换JSON字符串: ```cpp #include <iostream> #include <json/json.h> #include <afx.h> struct MyStruct { CString name; int age; bool isActive; }; int main() { // 初始化MFC结构体数据 MyStruct myStruct; myStruct.name = _T("John"); myStruct.age = 25; myStruct.isActive = true; // 创建Json::Value对象,并设置字段值 Json::Value root; root["name"] = CW2A(myStruct.name); root["age"] = myStruct.age; root["isActive"] = myStruct.isActive; // 将Json::Value对象转换JSON字符串 Json::StreamWriterBuilder writer; std::string jsonString = Json::writeString(writer, root); // 输出JSON字符串 std::cout << jsonString << std::endl; return 0; } ``` 在上述示例中,我们首先定义了一个MFC结构体`MyStruct`,其中包含了一个CString类型的`name`字段、一个整数类型的`age`字段和一个布尔类型的`isActive`字段。 然后,我们创建了一个Json::Value对象`root`,并将MFC结构体中的字段值分别赋给对应的JSON字段。 接着,我们使用JsonCpp库的`Json::StreamWriterBuilder`和`Json::writeString()`函数将Json::Value对象转换JSON字符串。 最后,我们将生成的JSON字符串输出到控制台。 运行以上代码,你会看到输出结果为: ``` {"name":"John","age":25,"isActive":true} ``` 希望这个示例能够帮助你将MFC结构体数据转换JSON字符串。如果有任何进一步的问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值