ASP.NET JSON文字列とエンティティークラスの変換例コード
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;///
using System.IO;
using System.Text;
///
/// Summary description for JsonHelper
///
public class JsonHelper
{
public JsonHelper()
{
//
// TODO: Add constructor logic here
//
}
///
/// JSON
///
///
///
/// JSON
public static string GetJson(T obj)
{
// System.ServiceModel.Web
/**
* ,System.Runtime.Serialization.Json; Json
* */
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
json.WriteObject(ms, obj);
string szJson = Encoding.UTF8.GetString(ms.ToArray());
return szJson;
}
}
///
/// JSON
///
///
/// JSON
///
public static T ParseFormJson(string szJson)
{
T obj = Activator.CreateInstance();
using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
return (T)dcj.ReadObject(ms);
}
}
}
エンティティークラスのテスト:
public class TestData
{
public TestData()
{
}
public int Id { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
}
テストページ:
<br> protected void Page_Load(object sender, EventArgs e)<br> {<br> string jsonStr = string.Empty;<br> List<TestData> tds = new List<TestData>();<br> // <br> for (int i = 1; i < 4; i++)<br> {<br> tds.Add(new TestData() { Id = i, Name = "jinho" + i, Sex = "male" });<br> } // list json <br> jsonStr = JsonHelper.GetJson<List<TestData>>(tds);<br> Response.Write(jsonStr);<br> this.Page.ClientScript.RegisterStartupScript(this.GetType(), "json", "getJson(" + jsonStr + ");", true);<br> }<br><br>
<br> function getJson(jsonStr) { // eval <br> var json = eval(jsonStr); // list <br> for (var i = 0; i < json.length; i++) {<br> alert(json[i].Id + "Name:" + json[i].Name);<br> }<br> }<br>
<br/><br/><br/> <form id="form1" runat="server"><br/> <div><br/><br/> </div><br/> </form><br/><br/><br/>
</code></pre>
<br/> json ! JsonHelper , !
<div class="clearfix">
<span id="art_bot" class="jbTestPos"/>
</div>
</div>
</div>
</div>