JSON--WEB SERVICE
Query ajax webservice:get 和 post
一、GET 方式
客户端
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/WebServices/ProductPropertyWebService.asmx/GetProductPropertyList",
dataType: "json",
anysc: false,
data: data,
success: RenderProperties,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown + ':' + textStatus); // 错误处理
}
});
服务器端
代码
public List<Property> GetProductPropertyList()
{
string classCode = HttpContext.Current.Request["classCode"]; // Get 方式,要在查询字符串里得到参数值
return PropertyManager.GetPropertySet(classCode, "zh-CN").DataList;
}
二、POST 方式
客户端
代码
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/WebServices/ProductPropertyWebService.asmx/GetProductPropertyList",
dataType: "json",
anysc: false,
data: data, // Post 方式,data参数不能为空"",如果不传参数,也要写成"{}",否则contentType将不能附加在Request Headers中。
success: RenderProperties,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown + ':' + textStatus); // 错误处理
}
});
服务器端
代码
public List<Property> GetProductPropertyList(string classCode, string city) // Post 方式,参数对应JSON字段属性,并自动赋值直接使用
{
return PropertyManager.GetPropertySet(classCode, "zh-CN").DataList;
}
注意:GET方法与POST方法不同,有参数的时候,如果参数的值不是ASCII字符(比如中文),GET的参数要encodeURI编码,要不服务端接收到的数据为乱码。
复杂的Json数据提交
简单的Json 格式的数据如 { name:Yangjun, age:27 }
复杂的Json格式的数据,其实只是Json嵌套,比如: {name:yangjun, age:27, child:[{name:yangke, age:1},{name:yangbin, age:2}]}
如果是这种复杂的Json格式的数据要提交,并在Webservices中获取,然后根据这个Json格式的字符串,序列成.net对象,应该怎么做呢?
比如我要提交下面的数据:
客户端:
代码
{"PropertyId":18, "PropertyType":"text", "PropertyValue":"号码是100"},
{"PropertyId":19, "PropertyType":"checkbox", "PropertyValue":"57|28"}]}
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/WebServices/ProductPropertyWebService.asmx/PostProductPropertyList",
anysc: false,
data: { propertyList: productPropertyTemplate },
dataType: "json",
success: function (result) { alert(result.d) },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown + ':' + textStatus);
}
});
服务器端:
1、要反序列化Json字符为.net对象,有比较多的开源类库,我使用的是.net 3.5版本以上自带的DataContractJsonSerializer,写一个辅助类:
代码
/// Json序列化和反序列化的帮助方法
/// </summary>
public class JsonHelper
{
/// <summary>
/// JSON序列化:把对象序列化成Json格式的字符串
/// </summary>
public static string JsonSerializer<T>(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;
}
/// <summary>
/// JSON反序列化:根据Json格式的字符串,反序列化成对象
/// </summary>
public static T JsonDeserialize<T>(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、因为要反序列化成相应的对象,所以先构造两个对象类,注意每个类和类的字段前面的特性修改符:
代码
public class MProductProperty
{
[DataMember(Order = 0, IsRequired = true)]
public int ProductId { set; get; }
[DataMember(Order = 1, IsRequired = true)]
public List<MProperty> 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、接收并处理Json数据的Web方法:
代码
[ScriptMethod(UseHttpGet = true)]
public string PostProductPropertyList()
{
string jsonString = HttpContext.Current.Request["propertyList"];
var productProperty = JsonHelper.JsonDeserialize<MProductProperty>(jsonString); // productProperty 成功反序列化成MProductProperty的对象
//返回接收成功标识
return "postsuccess";
}
您可能感兴趣的文章:
JSON--WEB SERVICE的更多相关文章
- 通过ajax访问Tomcat服务器web service接口时出现No 'Access-Control-Allow-Origin' header问题的解决办法
问题描述 通过ajax访问Web服务器(Tomcat7.0.42)中的json web service接口的时候,报以下跨域问题: XMLHttpRequest cannot load http:// ...
- asp.net项目下的web service返回json数据问题
App_Code目录下放置WebService.cs文件,文件内容如: using System; using System.Collections.Generic; using System.Dat ...
- 基于Web Service的客户端框架搭建一:C#使用Http Post方式传递Json数据字符串调用Web Service
引言 前段时间一直在做一个ERP系统,随着系统功能的完善,客户端(CS模式)变得越来越臃肿.现在想将业务逻辑层以下部分和界面层分离,使用Web Service来做.由于C#中通过直接添加引用的方来调用 ...
- [转贴] ASP.NET -- Web Service (.asmx) & JSON
[转贴] ASP.NET -- Web Service (.asmx) & JSON 以前没做过,但临时被要求 ASP.NET Web Service 要传回 JSON格式 找到网络上两篇好文 ...
- WCF、Web API、WCF REST、Web Service比较
原文地址:http://www.dotnet-tricks.com/Tutorial/webapi/JI2X050413-Difference-between-WCF-and-Web-API-and- ...
- Web Service和WCF的区别。其实二者不属于一个范畴!!!
Web Service和WCF的区别 [1]Web Service:严格来说是行业标准,也就是Web Service 规范. 它有一套完成的规范体系标准,而且在持续不断的更新完善中. 它使用XML扩展 ...
- Difference between WCF and Web API and WCF REST and Web Service
The .Net framework has a number of technologies that allow you to create HTTP services such as Web S ...
- 【完全开源】百度地图Web service API C#.NET版,带地图显示控件、导航控件、POI查找控件
目录 概述 功能 如何使用 参考帮助 概述 源代码主要包含三个项目,BMap.NET.BMap.NET.WindowsForm以及BMap.NET.WinformDemo. BMap.NET 对百度地 ...
- WCF 、Web API 、 WCF REST 和 Web Service 的区别
WCF .Web API . WCF REST 和 Web Service 的区别 The .Net framework has a number of technologies that allow ...
- Consuming a RESTful Web Service
本篇文章将介绍使用Spring来建立RESTful的Web Service. 我们通过一个例子来说明这篇文章:这个例子将会使用Spring的RestTemplate来从Facebook的提供的API中 ...
随机推荐
- flex布局 居中
display:flex;justify-content: center;检查侧轴是否居中,比如古代竖着写字,检查字是否在每条竹简的中央. display:flex;align-items: cent ...
- MySQL进阶之存储引擎MyISAM与InnoDB的区别
一.存储引擎(表类型) 通常意义上,数据库就是数据的集合,具体到计算机数据库可以是存储器上一些文件的集合或一些内存数据的集合.我们通常说的MySQL数据库.sql Server数据库等其实是数据库管理 ...
- 在vue项目中显示实时时间(年月日时分秒)
1.在data中定义一个变量,存储时间 data(){ return { nowTime:'' } }, 2.给定一个div <div>{{nowTime}}</div> 3. ...
- Python之路Day08
文件操作 open() -- 打开 open通过Python控制操作系统打开文件 f=open('文件路径',mode='r',encoding='utf-8') mode -- 不写就默认是r f ...
- centos 部署 aspnetMVC 网页
在Linux上运行ASP.NET网站或WebApi的传统步骤是,先安装libgdiplus,再安装mono,然后安装Jexus.在这个过程中,虽然安装Jexus是挺简便的一件事,但是安装mono就相对 ...
- Vue之生命周期activated与created使用
created activated 触发顺序 组件创建最初始 created => mounted =>activated 触发次数 只在组件刚创建时创建 在使用keep-alive标 ...
- jdk8-》reduce操作
什么是reduce操作 聚合操作,中⽂意思是 “减少” 根据⼀定的规则将Stream中的元素进⾏计算后返回⼀个唯⼀的值 常⽤⽅法⼀: Optional<T> reduce(BinaryOp ...
- 洛谷P1086 花生采摘
https://www.luogu.org/problem/P1086 #include <bits/stdc++.h> using namespace std; typedef long ...
- 基于Java+HttpClient+TestNG的接口自动化测试框架(八)------ 针对文件的处理
在实际的接口测试中,有时需要根据情况进行文件的上传和下载.在文件数量比较小的时候,我们当然可以直接处理(比如若干个接口都用一个文件).但是,如果我们上传的文件需要使用不同文件夹里不同的文件,而且数量又 ...
- Android 开发压缩图片
private Bitmap imageZoom(int position , Bitmap bitMap) { //图片允许最大空间 double maxSize =2 ...