[C#] How to Serialize XML to JSON Using Json.NET

발행일: Jan, 2025
조회수: 0
단어수: 76

Table of Contents

Introduction

 These days, when exchanging messages between different apps or services, complex structured data is mostly converted to JSON. Of course, there are still many places that use XML. Therefore, there are cases where the data received in XML needs to be serialized to JSON and stored or sent to another node.

 In such cases, you can easily serialize it with just a method call using Json.NET.


Serialization

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 json = JsonConvert.SerializeXmlNode(doc);

Console.WriteLine(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"
//       }
//     ]
//   }
// }

Original text: https://www.newtonsoft.com/json/help/html/ConvertXmlToJson.htm


태그#JSON#XML#serialization#Json.NET#data exchange#structured data

JUNA BLOG VISITORS

오늘0
Total0