软件编程
位置:首页>> 软件编程>> C#编程>> C#中使用JSON.NET实现JSON、XML相互转换

C#中使用JSON.NET实现JSON、XML相互转换

作者:hebedich  发布时间:2022-12-11 04:34:12 

标签:C#,JSON,XML

官方 JSON.NET 地址
http://james.newtonking.com/pages/json-net.aspx

XML TO JSON


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"
//   }
//  ]
// }
//}

JSON TO XML


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>

DEMO:JSON TO XML


string json_str = "{\"a\":\"a\",\"b\":\"b\"}";
//json 的字符串需要按照这个格式 书写,否则会报错
string json = @"{
""?xml"": {
 ""@version"": ""1.0"",
 ""@standalone"": ""no""
},
""root"":" + json_str + "}";

if (!string.IsNullOrEmpty(json))
{
 XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

}
0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com