サーバー側
コード
コードをコピー
コードは次のとおりです。
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)] // UseHttpGet = false
public List
GetProductPropertyList(string classCode, string city) // Post メソッド、パラメータJSON フィールドのプロパティに対応し、 { dataType: "json"、
success: function (result) {alert(result.d) }、error: function (XMLHttpRequest, textStatus) , errorThrown) { alert(errorThrown ':' textStatus) } });
Server side:
1. To deserialize Json characters into .net objects, there are many open source libraries. I use the DataContractJsonSerializer that comes with .net version 3.5 or above. Write an auxiliary class:
Code
///
/// Helper methods for Json serialization and deserialization
///
public class JsonHelper
{
/// /// JSON serialization: serialize objects into Json format strings
///
public static string JsonSerializer(T t)
{
var ser = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms .ToArray());
ms.Close();
return jsonString;
}
///
/// JSON deserialization: according to Json format String, deserialized into object
///
public static T JsonDeserialize(string jsonString)
{
var ser = new DataContractJsonSerializer(typeof(T)) ;
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
var obj = (T)ser.ReadObject(ms);
return obj;
}
}
2. Because it needs to be deserialized into corresponding objects, two object classes are constructed first. Pay attention to the characteristic modifiers in front of each class and the field of the class:
Code
[DataContract]
public class MProductProperty
{
[DataMember(Order = 0, IsRequired = true)]
public int ProductId { set; get; }
[DataMember(Order = 1, IsRequired = true)]
public List PropertyList { set ; get; }
}
public class MProperty
{
[DataMember(Order = 0, IsRequired = true)]
public int PropertyId { set; get; }
[DataMember (Order = 1, IsRequired = true)]
public string PropertyType { set; get; }
[DataMember(Order = 2, IsRequired = true)]
public string PropertyValue { set; get; }
}
3. Web method for receiving and processing Json data:
Code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string PostProductPropertyList()
{
string jsonString = HttpContext.Current .Request["propertyList"];
var productProperty = JsonHelper.JsonDeserialize(jsonString); // productProperty is successfully deserialized into an MProductProperty object
//Return the reception success indicator
return "postsuccess" ;
}