首页 > 其他分享 >Json.NET Converting between JSON and XML

Json.NET Converting between JSON and XML

时间:2023-12-21 15:47:59浏览次数:48  
标签:XML www http name Json JSON com

 

 

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.

Conversion Rules
  • 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.

Note Note

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.

SerializeXmlNode

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.

Converting XML to JSON with SerializeXmlNode Copy
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.

Attribute to Force a JSON Array Copy
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"
//    ]
//  }
//}
DeserializeXmlNode

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.

Converting JSON to XML with DeserializeXmlNode Copy
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>
See Also

Reference

XmlNodeConverter JsonConvert  

标签:XML,www,http,name,Json,JSON,com
From: https://www.cnblogs.com/webenh/p/17919205.html

相关文章

  • 使用Newtonsoft.Json进行Json与XML相互转换
    XML的解析得考虑子节点父节点,让人头昏眼花,而JSON的解析好像没啥难度。今天突然发现Newtonsoft.Json中有关于Json和XML互转的方法,所以顺带记录总结一下。一、关于Newtonsoft.JsonNewtonsoft.Json(Json.Net)是一款.NET中开源的Json序列化和反序列化类库。Json.Net是一个读写Json效......
  • C# xml与对象相互转换
    例如:1.对象转xml(对象序列化为xml) stringstrImage=XmlSerializeHelper.Serialize<List<ImageSingle>>(imageList);2.xml转对象(反序列化) Imagebojimag=XmlSerializeHelper.DeSerialize<Image>(strimage);该序列化处理类如下: usingSystem;usingSys......
  • Json.Net Deserialize a Collection from BSON
    DeserializeaCollectionfromBSON(newtonsoft.com)Thissamplesets ReadRootValueAsArray to true sotherootBSONvalueiscorrectlyreadasanarrayinsteadofanobjectanddeserializesBSONtoacollection.SampleTypesCopypublicclassEv......
  • cjson 用法
     1、修改字典的值cJSON_SetValuestring(objectItem,value)//先获取objectTempPtr=cJSON_GetObjectItem(TempPtr,"nm");//修改该object的值cJSON_SetValuestring(TempPtr,"guxiangdehai");2、删除数组里面的值cJSON_DeleteItemFromArray(Array,index);//Array要......
  • fastjson2
    什么是JSONJSON是一种轻量级的数据交换格式。它基于ECMAScript的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构是的JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。JSON语法使用大括号......
  • Fastjson2基础使用以及底层序列化/反序列化实现探究
    来自于:https://www.cnblogs.com/6b7b5fc3/p/17134421.html1Fastjson2简介Fastjson2是Fastjson的升级版,特征:协议支持:支持JSON/JSONB两种协议部分解析:可以使用JSONPath进行部分解析获取需要的值语言支持:Java/Kotlin场景支持:Android8+/服务端其他特性支持:GraalNative-Image......
  • json.NewDecode用法
    Go使用RFC3339进行编码,如果控制生成的json,只需将2022-04-03T00:00:00.000更改为2022-04-03T00:00:00.000Z。例如,这是有效的。typeContractstruct{ContractId*int`json:"contract_id"`CompanyId*int`json:"company_id"`Dat......
  • XML操作
    XML操作因XML的易于读取和修改,因此可以存放程序的可配置项C#中的XML操作通过ConfigurationManager类读取通过该方法只能实现Get操作。并且在Winform框架下,无法实现配置文件的热加载privatestaticstringapiUrl=ConfigurationManager.AppSettings["Url"];通过XmlDo......
  • 【SpringBootWeb入门-16】Mybatis-基础操作-多条件查询操作&XML文件配置SQL
    1、章节回顾上一篇文章我们讲解了Mybatis的增改查操作,本篇继续学习Mybatis的复杂查询操作(多条件查询)。2、增删改查操作-多条件查询操作根据条件姓名、性别、入职时间来查询员工表emp数据,其中员工姓名支持模糊匹配,性别进行精确匹配,入职时间进行范围查询,查询结果按照最后修改时间......
  • OS模块和JSON模块
    OS模块和JSON模块【一】OS模块【二】JSON模块【1】序列化与反序列化序列化和反序列化是计算机科学中数据处理中的两个过程,用于将数据从一种格式转换为另一种格式。这两个过程通常称为编码和解码。序列化是将数据结构或对象转换为字节序列的过程,使得数据可以以一种易于传输......