如何传送自定义json数据并解析处理
1:我这里自定义一个json数据 如下所示:
var jsonData = [
{"Id":20547,"Name":"中南大学","NameEn":"central-south university","AreaId":190},
{"Id":20548,"Name":"湖南大学","NameEn":"Hunan university","AreaId":190},
{"Id":20549,"Name":"湖南师范大学","NameEn":"hunan normal university","AreaId":190}
];
2:把这个json数据传递给后台处理
$.ajax({
type: 'post',
async: false,
url: "serviceHandle/Test.asmx/TestJSON",
data: { xxx: JSON.stringify(jsonData) },
success: function (si) {
alert(si);
},
error: function (err) {
alert(err.error);
}
});
3:后台的webService服务如下进行解析处理
[WebMethod]
public void TestJSON()
{
HttpRequest request = HttpContext.Current.Request;
string objName = request["xxx"];
List<School> list_sc = getOneJson(objName);
}
getOneJson方法如下所示:
public static List<School> getOneJson(string jsonText)
{
List<School> list = new List<School>();
JavaScriptSerializer js = new JavaScriptSerializer();
object obj = js.DeserializeObject(jsonText);
foreach (object item in ((object[])(js.DeserializeObject(jsonText))))
{
School model = new School();
model.Id = ((Dictionary<string, object>)item)["Id"].ToString();
model.Name = ((Dictionary<string, object>)item)["Name"].ToString();
model.NameEn = ((Dictionary<string, object>)item)["NameEn"].ToString();
model.AreaId = ((Dictionary<string, object>)item)["AreaId"].ToString();
list.Add(model);
}
return list;
}
当然您得声明一个json格式的类以方便序列化
public class School
{
[System.Runtime.Serialization.DataMember]
public string Id { get; set; }
[System.Runtime.Serialization.DataMember]
public string Name { get; set; }
[System.Runtime.Serialization.DataMember]
public string NameEn { get; set; }
[System.Runtime.Serialization.DataMember]
public string AreaId { get; set; }
}