是否有一个简单的方法来填充我的c#对象与JSON对象通过AJAX传递?
这是使用JSON.stringify从页面传递给c# WEBMETHOD的JSON对象
{
"user": {
"name": "asdf",
"teamname": "b",
"email": "c",
"players": ["1", "2"]
}
}
接收JSON对象的c# webmethod
[WebMethod]
public static void SaveTeam(Object user)
{
}
c#类,表示传递给WebMethod的JSON对象的对象结构
public class User
{
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
JavaScript Serializer:需要使用System.Web.Script.Serialization;
public class JavaScriptSerializerDeSerializer<T>
{
private readonly JavaScriptSerializer serializer;
public JavaScriptSerializerDeSerializer()
{
this.serializer = new JavaScriptSerializer();
}
public string Serialize(T t)
{
return this.serializer.Serialize(t);
}
public T Deseralize(string stringObject)
{
return this.serializer.Deserialize<T>(stringObject);
}
}
数据契约序列化器:需要使用System.Runtime.Serialization.Json;
泛型类型T应该在数据契约中更多地序列化
public class JsonSerializerDeserializer<T> where T : class
{
private readonly DataContractJsonSerializer jsonSerializer;
public JsonSerializerDeserializer()
{
this.jsonSerializer = new DataContractJsonSerializer(typeof(T));
}
public string Serialize(T t)
{
using (var memoryStream = new MemoryStream())
{
this.jsonSerializer.WriteObject(memoryStream, t);
memoryStream.Position = 0;
using (var sr = new StreamReader(memoryStream))
{
return sr.ReadToEnd();
}
}
}
public T Deserialize(string objectString)
{
using (var ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes((objectString))))
{
return (T)this.jsonSerializer.ReadObject(ms);
}
}
}