C#中使用JSON.NET實(shí)現(xiàn)JSON、XML相互轉(zhuǎn)換
更新時(shí)間:2015年11月20日 09:41:06 投稿:hebedich
這篇文章主要介紹了C#中使用JSON.NET實(shí)現(xiàn)JSON、XML相互轉(zhuǎn)換的相關(guān)代碼及示例,需要的朋友可以參考下
官方 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 的字符串需要按照這個(gè)格式 書寫,否則會(huì)報(bào)錯(cuò)
string json = @"{
""?xml"": {
""@version"": ""1.0"",
""@standalone"": ""no""
},
""root"":" + json_str + "}";
if (!string.IsNullOrEmpty(json))
{
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
}
相關(guān)文章
Unity實(shí)現(xiàn)手機(jī)搖一搖震動(dòng)
這篇文章主要為大家詳細(xì)介紹了untiy實(shí)現(xiàn)手機(jī)搖一搖震動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11
C#使用ADO.Net連接數(shù)據(jù)庫與DbProviderFactory實(shí)現(xiàn)多數(shù)據(jù)庫訪問
這篇文章介紹了C#使用ADO.Net連接數(shù)據(jù)庫與DbProviderFactory實(shí)現(xiàn)多數(shù)據(jù)庫訪問的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05
C#打包應(yīng)用程序,與.NETFramework介紹
C#打包應(yīng)用程序,與.NETFramework介紹,需要的朋友可以參考一下2013-05-05

