C XML与Json转换实例详解,如何高效实现互转?
- 行业动态
- 2025-03-04
- 2
System.Text.Json
命名空间中的
JsonSerializer
类可以轻松地在 XML 和 JSON 之间进行转换。以下是一个详细的示例,展示了如何在 C# 中实现这一功能。# 1. 引入必要的命名空间确保在你的代码文件中引入必要的命名空间:“
csharp,using System;,using System.Text.Json;,using System.Text.Json.Serialization;,using System.Xml;,using System.Xml.Linq;,
`
# 2. 定义数据模型定义一个数据模型,该模型将用于序列化和反序列化操作。我们定义一个简单的
Person
类:
`
csharp,public class Person,{, public string Name { get; set; }, public int Age { get; set; },},
`
# 3. 从 JSON 转换为 XML要将 JSON 转换为 XML,可以使用
JsonSerializer
将 JSON 字符串反序列化为对象,然后使用
XElement
将对象序列化为 XML:
`
csharp,string json = "{"Name": "John Doe", "Age": 30}";// 反序列化为 Person 对象,Person person = JsonSerializer.Deserialize(json);// 将 Person 对象序列化为 XML,XElement xml = new XElement("Person",, new XElement("Name", person.Name),, new XElement("Age", person.Age),);Console.WriteLine(xml.ToString());,
`
# 4. 从 XML 转换为 JSON要从 XML 转换为 JSON,可以使用
XElement
解析 XML 数据,然后使用
JsonSerializer
将对象序列化为 JSON:
`
csharp,string xmlString = "Jane Doe25";// 解析 XML 数据,XElement xml = XElement.Parse(xmlString);// 将 XML 数据映射到 Person 对象,Person person = new Person,{, Name = xml.Element("Name")?.Value,, Age = int.Parse(xml.Element("Age")?.Value),};// 将 Person 对象序列化为 JSON,string json = JsonSerializer.Serialize(person);Console.WriteLine(json);,
`
# 5. 完整示例代码以下是完整的示例代码,展示了如何进行 JSON 和 XML 之间的相互转换:
`
csharp,using System;,using System.Text.Json;,using System.Text.Json.Serialization;,using System.Xml;,using System.Xml.Linq;class Program,{, public static void Main(), {, // JSON to XML, string json = "{"Name": "John Doe", "Age": 30}";, Person person = JsonSerializer.Deserialize(json);, XElement xml = new XElement("Person",, new XElement("Name", person.Name),, new XElement("Age", person.Age), );, Console.WriteLine("JSON to XML:");, Console.WriteLine(xml.ToString()); // XML to JSON, string xmlString = "Jane Doe25";, XElement xmlElement = XElement.Parse(xmlString);, Person anotherPerson = new Person, {, Name = xmlElement.Element("Name")?.Value,, Age = int.Parse(xmlElement.Element("Age")?.Value), };, string anotherJson = JsonSerializer.Serialize(anotherPerson);, Console.WriteLine(",XML to JSON:");, Console.WriteLine(anotherJson);, },}public class Person,{, public string Name { get; set; }, public int Age { get; set; },},
“运行上述代码,你将看到 JSON 转换为 XML 以及 XML 转换为 JSON 的结果。这种方法利用了 C# 的强大功能,使得在不同数据格式之间进行转换变得简单而高效。
C# XML与Json之间相互转换实例详解
在现代软件开发中,XML和JSON是两种常见的数据交换格式,C#提供了多种方式来进行这两种格式之间的转换,本文将详细介绍如何在C#中实现XML与JSON之间的相互转换,包括使用System.Xml.Linq
命名空间处理XML和使用Newtonsoft.Json
库处理JSON。
准备工作
确保你的项目中已经安装了Newtonsoft.Json
库,你可以通过NuGet包管理器安装:
Install-Package Newtonsoft.Json
XML转JSON
假设我们有以下XML数据:
<Person> <Name>John Doe</Name> <Age>30</Age> <Email>john.doe@example.com</Email> </Person>
我们可以使用XDocument
类来加载并解析这个XML,然后使用JsonConvert
类将其转换为JSON格式。
步骤:
1、引入必要的命名空间:
using System; using System.Xml.Linq; using Newtonsoft.Json;
2、加载XML数据:
string xml = @"<Person><Name>John Doe</Name><Age>30</Age><Email>john.doe@example.com</Email></Person>"; XDocument xDoc = XDocument.Parse(xml);
3、将XML转换为JSON:
string json = JsonConvert.SerializeXNode(xDoc, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
输出结果:
{ "Person": { "Name": "John Doe", "Age": "30", "Email": "john.doe@example.com" } }
JSON转XML
我们来看如何将JSON数据转换回XML格式,假设我们有以下JSON数据:
{ "Person": { "Name": "Jane Doe", "Age": 25, "Email": "jane.doe@example.com" } }
我们可以使用JsonConvert
类来解析JSON数据,然后使用XDocument
类将其转换为XML格式。
步骤:
1、引入必要的命名空间:
using System; using System.Xml.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq;
2、解析JSON数据:
string json = @"{ ""Person"": { ""Name"": ""Jane Doe"", ""Age"": 25, ""Email"": ""jane.doe@example.com"" } }"; JObject jObj = JObject.Parse(json);
3、将JSON转换为XML:
XDocument xDoc = new XDocument(new XElement("Person")); foreach (var property in jObj["Person"]) { xDoc.Root.Add(new XElement(property.Key, property.Value)); } string xml = xDoc.ToString(); Console.WriteLine(xml);
输出结果:
<Person> <Name>Jane Doe</Name> <Age>25</Age> <Email>jane.doe@example.com</Email> </Person>
复杂对象转换示例
对于更复杂的对象,比如包含嵌套结构或数组的JSON/XML,可以使用类似的方法,但需要递归处理嵌套元素,以下是一个包含嵌套结构的示例:
XML数据:
<Employees> <Employee> <Id>1</Id> <Name>John Doe</Name> <Department>HR</Department> </Employee> <Employee> <Id>2</Id> <Name>Jane Smith</Name> <Department>Engineering</Department> </Employee> </Employees>
JSON数据:
{ "Employees": [ { "Id": 1, "Name": "John Doe", "Department": "HR" }, { "Id": 2, "Name": "Jane Smith", "Department": "Engineering" } ] }
XML转JSON:
string xml = @"<Employees><Employee><Id>1</Id><Name>John Doe</Name><Department>HR</Department></Employee><Employee><Id>2</Id><Name>Jane Smith</Name><Department>Engineering</Department></Employee></Employees>"; XDocument xDoc = XDocument.Parse(xml); string json = JsonConvert.SerializeXNode(xDoc, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);
JSON转XML:
string json = @"{ ""Employees"": [ { ""Id"": 1, ""Name"": ""John Doe"", ""Department"": ""HR"" }, { ""Id"": 2, ""Name"": ""Jane Smith"", ""Department"": ""Engineering"" } ] }"; JObject jObj = JObject.Parse(json); XDocument xDoc = new XDocument(new XElement("Employees")); foreach (var employee in jObj["Employees"]) { XElement empElem = new XElement("Employee"); foreach (var property in employee) { empElem.Add(new XElement(property.Key, property.Value)); } xDoc.Root.Add(empElem); } string xml = xDoc.ToString(); Console.WriteLine(xml);
FAQs
Q1: 如果XML或JSON数据结构非常复杂,有没有更简单的方法进行转换?
A1: 对于非常复杂的数据结构,可以考虑使用第三方库如AutoMapper
,它可以自动映射复杂对象,减少手动编写转换代码的工作量,也可以自定义序列化和反序列化逻辑,以更好地控制转换过程。
Q2: 如何处理XML和JSON中的日期时间格式?
A2: 在转换过程中,日期时间格式可能会发生变化,为了保持一致性,可以在序列化和反序列化时指定日期时间格式,使用JsonSerializerSettings
来设置日期时间的格式:
JsonSerializerSettings settings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc }; string json = JsonConvert.SerializeXNode(xDoc, Newtonsoft.Json.Formatting.Indented, settings);
通过以上方法,你可以在C#中轻松地实现XML与JSON之间的相互转换,无论是简单的数据结构还是复杂的嵌套对象。