Json.NET Converting between JSON and XML
Json.NET supports converting JSON to XML and vice versa using the XmlNodeConverter.
Elements, attributes, text, comments, character data, processing instructions, namespaces, and the XML declaration are all preserved when converting between the two. The only caveat is that it is possible to lose the order of differently named nodes at the same level when they are grouped together into an array.
Elements remain unchanged.
Attributes are prefixed with an @ and should be at the start of the object.
Single child text nodes are a value directly against an element, otherwise they are accessed via #text.
The XML declaration and processing instructions are prefixed with ?.
Character data, comments, whitespace and significant whitespace nodes are accessed via #cdata-section, #comment, #whitespace and #significant-whitespace respectively.
Multiple nodes with the same name at the same level are grouped together into an array.
Empty elements are null.
If the XML created from JSON doesn't match what you want, then you will need to convert it manually. The best approach to do this is to load your JSON into a LINQ to JSON object like JObject or JArray and then use LINQ to create an XDocument. The opposite process, using LINQ with an XDocument to create a JObject or JArray, also works. You can find out more about using LINQ to JSON with LINQ here.
|
The version of Json.NET being used in your application will change what XML conversion methods are available. SerializeXmlNode/DeserializeXmlNode are available when the framework supports XmlDocument; SerializeXNode/DeserializeXNode are available when the framework supports XDocument. |
The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it to JSON text.
string xml = @"<?xml version='1.0' standalone='no'?>
<root>
<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
</person>
<person id='2'>
<name>Louis</name>
<url>http://www.yahoo.com</url>
</person>
</root>"; XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); string jsonText = JsonConvert.SerializeXmlNode(doc);
//{
// "?xml": {
// "@version": "1.0",
// "@standalone": "no"
// },
// "root": {
// "person": [
// {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com"
// },
// {
// "@id": "2",
// "name": "Louis",
// "url": "http://www.yahoo.com"
// }
// ]
// }
//}
Because multiple nodes with the same name at the same level are grouped together into an array, the conversion process can produce different JSON depending on the number of nodes. For example, if some XML for a user has a single <Role> node, then that role will be text against a JSON "Role" property, but if the user has multiple <Role> nodes, then the role values will be placed in a JSON array.
To fix this situation a custom XML attribute can be added to force a JSON array to be created.
string xml = @"<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role>Admin1</role>
</person>"; XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc);
//{
// "person": {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com",
// "role": "Admin1"
// }
//} xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>"; doc = new XmlDocument();
doc.LoadXml(xml); json = JsonConvert.SerializeXmlNode(doc);
//{
// "person": {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com",
// "role": [
// "Admin"
// ]
// }
//}
The second helper method on JsonConvert is DeserializeXmlNode(). This method takes JSON text and deserializes it into an XmlNode.
Because valid XML must have one root element, the JSON passed to DeserializeXmlNode should have one property in the root JSON object. If the root JSON object has multiple properties, then the overload that also takes an element name should be used. A root element with that name will be inserted into the deserialized XmlNode.
string json = @"{
'?xml': {
'@version': '1.0',
'@standalone': 'no'
},
'root': {
'person': [
{
'@id': '1',
'name': 'Alan',
'url': 'http://www.google.com'
},
{
'@id': '2',
'name': 'Louis',
'url': 'http://www.yahoo.com'
}
]
}
}";
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
// <?xml version="1.0" standalone="no"?>
// <root>
// <person id="1">
// <name>Alan</name>
// <url>http://www.google.com</url>
// </person>
// <person id="2">
// <name>Louis</name>
// <url>http://www.yahoo.com</url>
// </person>
// </root>
Json.NET Converting between JSON and XML的更多相关文章
- Json、JavaBean、Map、XML之间的互转
思路是JavaBean.Map.XML都可以用工具类很简单的转换为Json,进而实现互相转换 1.Map.XML与Json互转 mvn依赖 <dependency> <groupId ...
- 常用模块之 shutil,json,pickle,shelve,xml,configparser
shutil 高级的文件.文件夹.压缩包 处理模块 shutil.copyfileobj(fsrc, fdst[, length]) 将文件内容拷贝到另一个文件中 import shutil shut ...
- 常用文件操作模块json,pickle、shelve和XML
一.json 和 pickle模块 用于序列化的两个模块 json,用于字符串 和 python数据类型间进行转换 pickle,用于python特有的类型 和 python的数据类型间进行转换 Js ...
- Java:JSON解析工具-org.json
一.简介 org.json是Java常用的Json解析工具,主要提供JSONObject和JSONArray类,现在就各个类的使用解释如下. 二.准备 1.在使用org.json之前,我们应该先从该网 ...
- json和jsonp(json是目的,jsonp是手段)
自己理解:JSON是一种数据交换格式,而JSONP是一种依靠开发人员的聪明才智创造出的一种非官方跨域数据交互协议.我们拿最近比较火的谍战片来打个比方,JSON是地下党们用来书写和交换情报的" ...
- javascript中字符串格式json如何转化成json对象
什么是JSON JSON(JavaScript Object Notation)是一种优美的JavaScript对象创建方法.JSON也是一种轻量级数据交换格式.JSON非常易于人阅读与编写,同时利于 ...
- JSON之三:获取JSON文本并解释(以google的天气API为例)
google提供了天气的api,以广州天气为例,地址为: http://api.openweathermap.org/data/2.5/weather?q=guangzhou 返回的结果为: { ...
- json解包与json封包
首先,对两个名词进行简单的说明: 1.NSData 用来存储二进制的数据类型.NSData类提供了一种简单的方式,它用来设置缓冲区.将文件的内容读入缓冲区,或将缓冲区的内容写到一个文件.不变缓冲区(N ...
- JSON以及Java转换JSON的方法(前后端常用处理方法)
)); map.put("arr", new String[] { "a", "b" }); map.put("func" ...
- c# 在.NET使用Newtonsoft.Json转换,读取,写入json
转自:http://blog.sina.com.cn/s/blog_70686f3a0101kemg.html 首先,大家要明白什么是json,了解更多关于json方面资料大家可以点击https:/ ...
随机推荐
- 重新点亮shell————文本搜索[九]
前言 简单整理一下文本搜索. 正文 文本搜索需要学下面: 元字符 扩展元字符 文件的查找命令find 例子1: 例子2(通配符): 例子3(正则表达): 例子4(可以根据文件类型匹配): 例子5(找到 ...
- Kafka的实现细节
Kafka的实现细节 一.Topic和Partition 在Kafka中的每一条消息都有一个topic.一般来说在我们应用中产生不同类型的数据,都可以设置不同的主题.一个主题一般会有多个消息的订阅者, ...
- vue使用 elementUI中el-upload的遇到的问题总结
使用场景,使用el-upload上传文件,选择文件后不立即上传到服务器上,点击提交按钮时与其他form表单数据一起提交,类似的需求,相信有很多小伙伴遇到,可能也会遇到跟我一起的问题,在这里记录一下 & ...
- lin-view-ui Vue 2.0 组件库
lin-view-ui 是一款基于 Vue.js 2.0 的前端 UI 组件库,主要集成了平时在开发中使用到的 UI 组件. 特性 基于 Vue 开发的 UI 组件 使用 npm + webpack ...
- Ubuntu22.04版本安装对应版本ROS教程 (小白2024年)
参考资料:(我是开了加速器,毕竟中间使用了github访问网址,国内免费加速器Steam++,开个github网站加速即可,不开我不知道行不行可以自己一试) ubuntu22.04安装ROS2 详细教 ...
- IDC:云效产品能力No.1,领跑中国DevOps市场
简介: 近日,全球领先的专业市场调查机构国际数据公司(IDC)发布了<IDC MarketScape:中国 DevOps 平台市场厂商评估,2022>报告.此报告中对中国主流 DevOps ...
- 动态尺寸模型优化实践之Shape Constraint IR Part II
简介: 在本系列分享中我们将介绍BladeDISC在动态shape语义下做性能优化的一些实践和思考.本次分享的是我们最近开展的有关shape constraint IR的工作,Part II 中我们将 ...
- 高效使用Java构建工具|Maven篇|云效工程师指北
简介:高效使用Java构建工具|Maven篇.众所周知,当前最主流的Java构建工具为Maven/Gradle/Bazel,针对每一个工具,我将分别从日常工作中常见的场景问题切入,例如依赖管理.构建 ...
- ACK正式支持对基于Alibaba Cloud Linux操作系统的集群进行等保加固
简介: 我们对基于Alibaba Cloud linux操作系统的ACK集群进行等保加固,意味着阿里云在云产品开发和交付的过程中将安全作为重要组成部分,将合规融入到产品的"血液"中 ...
- 日志服务SLS 助力识货 APP,解决业务数据采集查询监控问题
简介: 日志服务SLS 助力识货 APP,解决业务数据采集查询监控问题 更多存储标杆案例欢迎点击下方链接查看 阿里云存储标杆案例样板间 公司介绍识货APP是虎扑体育旗下的导购应用,致力于为广大年轻用户 ...