前端之家收集整理的这篇文章主要介绍了
Json.NET使用入门(四)【XML和JSON互转】,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
生命里复杂的不光是人与人之间,还是有理想中的自己和现实中的自己。使一切变复杂的,是我们无休止的欲望。因为欲望,一切得到的都是不再珍贵,一切得不到的才是好的。人心何时懂得知足,何时才能迎来幸福。
XJConverter.aspx内容:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="XJConverter.aspx.cs" Inherits="NewtonsoftDemo.XJConverter" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:Button ID="btnConvertJSONToXML" runat="server" Text="转换JSON to XML" OnClick="btnConvertJSONToXML_Click" />
</td>
<td>
<asp:Button ID="btnConvertXMLToJSON" runat="server" Text="转换 XML to JSON" style="height: 27px" OnClick="btnConvertXMLToJSON_Click" /><br />
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnConvertXMLtoJSONForceArray" runat="server" Text="转换 XML to JSON and 强制 array " OnClick="btnConvertXMLtoJSONForceArray_Click" />
</td>
<td>
<br />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
XJConverter.aspx.cs代码:
public partial class XJConverter : System.Web.UI.Page
{
protected void Page_Load(object sender,EventArgs e)
{
}
protected void btnConvertJSONToXML_Click(object sender,EventArgs e)
{
string json = @"{
'@Id': 1,'Email': 'james@example.com','Active': true,'CreatedDate': '2013-01-20T00:00:00Z','Roles': [
'User','Admin'
],'Team': {
'@Id': 2,'Name': 'Software Developers','Description': 'Creators of fine software products and services.'
}
}";
XNode node = JsonConvert.DeserializeXNode(json,"Root");
Response.Write(node.ToString());
}
protected void btnConvertXMLToJSON_Click(object sender,EventArgs e)
{
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);
Response.Write(json);
}
protected void btnConvertXMLtoJSONForceArray_Click(object sender,EventArgs e)
{
string xml = @"<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role>Admin1</role>
</person>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
Response.Write(json);
xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>";
doc = new XmlDocument();
doc.LoadXml(xml);
json = JsonConvert.SerializeXmlNode(doc);
Response.Write(json);
}
}
运行结果如图: