这是我的目标。
使用WCF Rest服务读取xml数据并返回JSON格式。
*我不想使用JSON.NET *
这是Sample XML数据。
<students>
<student>
<student_id>1111</student_id>
<student_name>
<student_title>Mr</student_title>
<student_first_name>Shi</student_first_name>
<student_last_name>Oki</student_last_name>
<level>2</level>
</student_name>
<student_address>
<student_address_line_one>JP</student_address_line_one>
<student_address_line_two>Japan</student_address_line_two>
<student_address_line_three>Tokyo, Japan</student_address_line_three>
<student_address_line_four>1234</student_address_line_four>
<student_address_line_five>Japan</student_address_line_five>
<zip_code>1234</zip_code>
</student_address>
<gender>Male</gender>
<phone_no>12345678</phone_no>
</student>
这是服务功能。
public string GetXmlDataToJsonUsingDataSet(string id)
{
string jsonClient = "";
string szXmlFile = "C:\\test.xml";
//load xmlFile
XmlDocument doc = new XmlDocument();
doc.Load(szXmlFile);
DataSet ds = new DataSet();
//ds.ReadXml(szXmlFile);
using (XmlReader xReader = new XmlNodeReader(doc.DocumentElement))
{
ds.ReadXml(xReader);
xReader.Close();
}
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataTable dt in ds.Tables)
{
object[] arr = new object[dt.Rows.Count];
object[] arrColumn;
for (int i = 0; i < dt.Rows.Count; i++)
{
arrColumn = new object[dt.Columns.Count];
int j = 0;
foreach (DataColumn column in dt.Columns)
{
arrColumn[j] = column.ColumnName + " : " + dt.Rows[i][column];
j++;
}
arr[i] = arrColumn;
}
dict.Add(dt.TableName, arr);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
jsonClient = jss.Serialize(dict);
return jsonClient;
}
这是[OperationContract]。
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "tjson/{id}")]
string GetXmlDataToJsonUsingDataSet(string id);
这是JSON结果。
{
"student":
[
[
"student_id : 1111",
"student_Id_0 : 0",
"gender : Male",
"phone_no : 12345678"
]
],
"student_name":
[
[
"student_title : Mr",
"student_first_name : Shi",
"student_last_name : Oki",
"level : 2",
"student_Id_0 : 0"
]
],
"student_address":
[
[
"student_address_line_one : JP",
"student_address_line_two : Japan",
"student_address_line_three : Tokyo, Japan",
"student_address_line_four : 1234",
"student_address_line_five : Japan",
"zip_code : 1234",
"student_Id_0 : 0"
]
]
}
这是我的专家JSON结果。
{
"student":
{
"student_id" : "1111",
"gender" : "Male",
"phone_no" : "12345678",
"student_name":
[
{
"student_title" : "Mr",
"student_first_name" : "Shi",
"student_last_name" : "Oki"
}
],
"student_address":
[
{
"student_address_line_one" : "JP",
"student_address_line_two" : "Japan",
"student_address_line_three" : "Tokyo, Japan",
"student_address_line_four" : "1234",
"student_address_line_five" : "Japan",
"zip_code" : "1234"
}
]
}
}
请帮忙!谢谢。