传送自定义json数据并解析处理实例

发布时间:2020-10-13编辑:脚本学堂
本文介绍了传送自定义json数据并解析处理的方法,一个解析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; }
}