https://blog.csdn.net/kfy2011/article/details/51774242

1、下载c语言的cJson库源码,库很小,只有两个文件cJSON.c和cJSON.h。下载地址:https://sourceforge.net/projects/cjson/

2、c++实现Xml和json互转

2.1、头文件

  1. #include "XmlJsonTransfer.h"
  2. //#include "cmsDebug.h"
  3. #include "WebSocket/src/cJSON.h"
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <stdio.h>
  7. #include <assert.h>
  8. #include <time.h>
  9. #include <iostream>
  10. using namespace std;

2.2、xml转json

  1. // 依赖cJSon,递归
  2. /*
  3. <doc><a a1="1" a2="2">123</a></doc> 转 {"doc": {"a": {"-a1": "1","-a2": "2","#text": "123"}}}
  4. */
  5. string Xml2Json(string strXml)
  6. {
  7. string pNext = strXml;
  8. cJSON * reJson = cJSON_CreateObject();
  9. cJSON * jsonArray = cJSON_CreateArray();
  10. string strArrayKey = "";
  11. int nPos = 0;
  12. while ((nPos = pNext.find("<")) >= 0)
  13. {
  14. // 获取第一个节点,如:<doc><a a1="1" a2="2">123</a></doc>
  15. int nPosS = pNext.find("<");
  16. int nPosE = pNext.find(">");
  17. if (nPosS < 0 || nPosE < 0)
  18. {
  19. printf("key error!");
  20. }
  21. string strKey = pNext.substr(nPosS+1, nPosE-nPosS-1);
  22. // 解释属性,如:<a a1="1" a2="2">
  23. cJSON * jsonVal = NULL;
  24. if ((nPos = strKey.find("=")) > 0)
  25. {
  26. jsonVal = cJSON_CreateObject();
  27. int nPos = strKey.find(" ");
  28. string temp = strKey.substr(nPos+1);
  29. strKey = strKey.substr(0, nPos);
  30. while((nPos = temp.find("=")) > 0)
  31. {
  32. int nPos1 = temp.find("=");
  33. int nPos2 = temp.find("\" ", nPos1 + 1);
  34. string strSubKey = temp.substr(0, nPos1);
  35. string strSubVal = temp.substr(nPos1+1);
  36. if (nPos2 > 0)
  37. strSubVal = temp.substr(nPos1+1, nPos2-nPos1-1);
  38. // 去除转义字符 \"
  39. if ((int)(nPos = strSubVal.find("\"")) >= 0)
  40. {
  41. int nEnd = strSubVal.find("\\", nPos+1);
  42. strSubVal = strSubVal.substr(nPos+1, nEnd-nPos-1);
  43. }
  44. cJSON_AddItemToObject(jsonVal, ("-" + strSubKey).c_str(), cJSON_CreateString(strSubVal.c_str()));
  45. if (nPos2 < 0)
  46. break;
  47. temp = temp.substr(nPos2+2);
  48. }
  49. }
  50. int nPosKeyE = pNext.find("</" + strKey + ">");
  51. if (nPosKeyE < 0)
  52. {
  53. printf("key error!");
  54. }
  55. // 获取节点内容,如<a a1="1" a2="2">123</a> 或 123
  56. string strVal = pNext.substr(nPosE+1, nPosKeyE-nPosE-1);
  57. if ((nPos = strVal.find("<")) >= 0)
  58. {
  59. // 包含子节点,如<a a1="1" a2="2">123</a>
  60. strVal = Xml2Json(strVal);
  61. if (jsonVal)
  62. {
  63. if (strVal != "")
  64. cJSON_AddItemToObject(jsonVal, "#text", cJSON_Parse(strVal.c_str()));
  65. }
  66. else
  67. {
  68. jsonVal = cJSON_Parse(strVal.c_str());
  69. }
  70. }
  71. else
  72. {
  73. // 不包含子节点,如123
  74. if (jsonVal)
  75. {
  76. if (strVal != "")
  77. cJSON_AddItemToObject(jsonVal, "#text", cJSON_CreateString(strVal.c_str()));
  78. }
  79. else
  80. {
  81. jsonVal = cJSON_CreateString(strVal.c_str());
  82. }
  83. }
  84. // 获取下一个节点
  85. pNext = pNext.substr(nPosKeyE + strKey.size() + 3);
  86. // 根据下一节点判断是否为数组
  87. int nPosNext = pNext.find("<");
  88. int nPosNextSame = pNext.find("<" + strKey + ">");
  89. if (strArrayKey != "" || (nPosNext>=0 && nPosNextSame>=0 && nPosNext==nPosNextSame))
  90. {
  91. // 数组
  92. cJSON_AddItemToArray(jsonArray, jsonVal);
  93. strArrayKey = strKey;
  94. }
  95. else
  96. {
  97. // 非数组
  98. cJSON_AddItemToObject(reJson, strKey.c_str(), jsonVal);
  99. }
  100. }
  101. if (strArrayKey != "")
  102. {
  103. cJSON_AddItemToObject(reJson, strArrayKey.c_str(), jsonArray);
  104. }
  105. string strJson = cJSON_Print(reJson);
  106. if(reJson)
  107. {
  108. cJSON_Delete(reJson);
  109. reJson = NULL;
  110. }
  111. return strJson;
  112. }

2.3、json转xml

  1. // 依赖cJSon,递归
  2. /*
  3. {"doc": {"a": {"-a1": "1","-a2": "2","#text": "123"}}}  转 <doc><a a1="1" a2="2">123</a></doc>
  4. */
  5. string Json2Xml(string strJson)
  6. {
  7. string strXml = "";
  8. cJSON *root = cJSON_Parse(strJson.c_str());
  9. if (!root)
  10. {
  11. printf("strJson error!");
  12. return "";
  13. }
  14. cJSON *pNext = root->child;
  15. if (!pNext)
  16. {
  17. return strJson;
  18. }
  19. int nPos = 0;
  20. while (pNext)
  21. {
  22. string strChild = cJSON_Print(pNext);
  23. string strVal = Json2Xml(strChild);
  24. if (pNext->string != NULL)
  25. {
  26. string strKey = pNext->string;
  27. if ((nPos=strKey.find("-")) == 0)
  28. {
  29. // 属性项
  30. strXml.append(" ");
  31. strXml.append(strKey.substr(1));
  32. strXml.append("=");
  33. strXml.append(strVal);
  34. if (pNext->next == NULL)
  35. strXml.append(">");
  36. }
  37. else if ((nPos=strKey.find("#")) == 0)
  38. {
  39. // 值
  40. strXml.append(">");
  41. strXml.append(strVal);
  42. }
  43. else if ((int)(strVal.find("=")) > 0 /*&& (int)(strVal.find("<")) < 0*/)
  44. {
  45. // 包含属性项的键值对
  46. strXml.append("<" + strKey);
  47. strXml.append(strVal);
  48. strXml.append("</" + strKey + ">");
  49. }
  50. else
  51. {
  52. // 修正底层无键的值数组的键,如:把<JUAN_XJ_preKey>123</JUAN_XJ_preKey>中的JUAN_XJ_preKey修正
  53. if ((int)strVal.find("JUAN_XJ_preKey") >= 0)
  54. {
  55. replace_all(strVal, "JUAN_XJ_preKey", strKey);
  56. strXml.append(strVal);
  57. }
  58. else
  59. {
  60. strXml.append("<" + strKey + ">");
  61. strXml.append(strVal);
  62. strXml.append("</" + strKey + ">");
  63. }
  64. }
  65. }
  66. else
  67. {
  68. // 不包含键的值数组, 如:["123", "456"],暂时转为<JUAN_XJ_preKey>123</JUAN_XJ_preKey>
  69. string strPreKey = "JUAN_XJ_preKey";
  70. strXml.append("<" + strPreKey + ">");
  71. strXml.append(strVal);
  72. strXml.append("</" + strPreKey + ">");
  73. }
  74. pNext = pNext->next;
  75. }
  76. return strXml;
  77. }

2.4、辅助函数

    1. // 替换字符串
    2. string&  replace_all(string& str, const string& old_value, const string& new_value)
    3. {
    4. while(true)
    5. {
    6. string::size_type   pos(0);
    7. if((pos=str.find(old_value)) != string::npos)
    8. str.replace(pos,old_value.length(),new_value);
    9. else
    10. break;
    11. }
    12. return   str;
    13. }

c++实现Xml和json互转【转】的更多相关文章

  1. JavaScript实现XML与JSON互转代码(转载)

    下面来分享一个关于JavaScript实现XML与JSON互转例子,这里面介绍了国外的三款xml转json的例子,希望这些例子能给你带来帮助. 最近在开发在线XML编辑器,打算使用JSON做为中间格式 ...

  2. SQL2008使用json.net实现XML与JSON互转

    借助CLR,首先实现字符串的互转,然后使用存储过程实现JSON2table     public class JsonFunction    {        /// <summary> ...

  3. JSONUtil(JAVA对象/List与json互转,xml与json互转)

    package com.chauvet.utils.json; import java.io.BufferedReader; import java.io.File; import java.io.F ...

  4. xml与json互转

    依赖包: <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib< ...

  5. C# :XML和JSON互转

    我们一般在用JSON或者XML作为数据交换的时候,可能定义一个没有真正意义方法的类,其实就是一个关于属性的数据结构,如果对于这种情况,可以将这个类对象作为中介,然后利用C#提供的序列化和反序列化的方法 ...

  6. xml和json互转

    开发过程中有些时候需要把xml和json互转,如某钱X接口入参和出参都是xml格式的,十分蛋疼.特写下面工具类,以留用. 需要引用jar: <!-- https://mvnrepository. ...

  7. Json、JavaBean、Map、XML之间的互转

    思路是JavaBean.Map.XML都可以用工具类很简单的转换为Json,进而实现互相转换 1.Map.XML与Json互转 mvn依赖 <dependency> <groupId ...

  8. c#通用配置文件读写类(xml,ini,json)

    .NET下编写程序的时候经常会使用到配置文件.配置文件格式通常有xml.ini.json等几种,操作不同类型配置文件需要使用不同的方法,操作较为麻烦.特别是针对同时应用不同格式配置文件的时候,很容易引 ...

  9. c#通用配置文件读写类与格式转换(xml,ini,json)

    .NET下编写程序的时候经常会使用到配置文件.配置文件格式通常有xml.ini.json等几种,操作不同类型配置文件需要使用不同的方法,操作较为麻烦.特别是针对同时应用不同格式配置文件的时候,很容易引 ...

随机推荐

  1. Linux驱动之平台设备

    <平台设备设备驱动> a:背景: 平台总线是Linux2.6的设备驱动模型中,关心总线,设备和驱动这3个实体.一个现实的Linux设备和驱动通常需要挂接在一种总线上(比如本身依附于PCI, ...

  2. 使用 IntraWeb (2) - Hello IntraWeb

    IntraWeb 比我相像中的更贴近 VCL, 传统的非可视组件在这里大都可用(其内部很多复合属性是 TStringList 类型的), 它的诸多可视控件也是从 TControl 继承下来的. 这或许 ...

  3. jquery json 格式教程

    介绍 我们知道AJAX技术能够使得每一次请求更加迅捷,对于每一次请求返回的不是整个页面,也仅仅是所需要返回的数据.通常AJAX通过返回XML格式的数据,然后再通过客户端复杂的JavaScript脚本解 ...

  4. USBDM Kinetis Debugger and Programmer

    Introduction The FRM-xxxx boards from Freescale includes a minimal SWD based debugging interface for ...

  5. Virtualenv教程

    虚拟环境简介 VirtualEnv用于在一台机器上创建多个独立的Python虚拟运行环境,多个Python环境相互独立,互不影响,它能够: 在没有权限的情况下安装新套件 不同应用可以使用不同的套件版本 ...

  6. TF400511: Your team has not defined any iterations to use as sprints

    tfs里面的冲刺对于开发团队来说, 是非常重要的一个功能,是团队开发进度的晴雨表: 但是如果从此死活出不来,怎么办呢? TF400511:您的团队尚未定义任何要用作冲刺 (sprint) 的迭代 TF ...

  7. IIS日志文件清理

    如何清除IIS日志以释放空间 打开“我的电脑”发现10GB容量的C盘只剩余355MB“可用空间”,已经严重不够用.如下图: 如果服务器的管理员并没有在C盘存储大容量文件,而IIS中站点的访问量又非常大 ...

  8. PostgreSQL学习手册(目录)

    原文地址:http://www.cnblogs.com/stephen-liu74/archive/2012/06/08/2315679.html 事实上之前有很长一段时间都在纠结是否有必要好好学习它 ...

  9. CATransition 实践

    时间差不够,导致闪屏 CATransition *animation = [CATransition animation]; animation.delegate = self; animation. ...

  10. uitextfield 设置为密码框显示

    uitextfield 设置为密码框显示: 在xib中,将文本secure的复选框选中即可.