是否有一个简单的方法来填充我的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);
}
}
}
如果您使用的是。net 3.5或更高版本,为了保持您的选择余地,这里有一个封装好的示例,您可以使用泛型直接从框架中使用。正如其他人所提到的,如果不仅仅是简单的对象,那么就应该使用JSON.net。
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
你需要:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;