当前位置: 移动技术网 > IT编程>开发语言>c# > C#中使用JSON.NET实现JSON、XML相互转换

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

官方 json.net 地址

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);
   
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网