android 调用wcf json,(原创)jQuery调用WCF返回JSON对象

这篇博客介绍了如何通过创建自定义数据类型JsonResult,构建WCF服务并定义服务接口,实现客户端以JSON格式调用和接收数据。具体步骤包括定义数据合同,实现服务接口,客户端使用AJAX进行调用,并在web.config中配置WCF行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:自定义数据类型(最终此类型以JSON的格式返回到客户端供解析)

JsonResult.cs 文件代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Runtime.Serialization;

[DataContract]

public class JsonResult

{

public

JsonResult(string name, string address, string phone)

{

_name = name ;

_address = address;

_phone = phone;

}

private

string _name;

[DataMember]

public

string Name

{

get { return _name; }

set { _name = value; }

}

private

string _address;

[DataMember]

public

string Address

{

get { return _address; }

set { _address = value; }

}

private

string _phone;

[DataMember]

public

string Phone

{

get { return _phone; }

set { _phone = value; }

}

}

第二步:构建wcf服务

Service.svc 文件代码:

Service="Service" CodeBehind="~/App_Code/Service.cs"

%>

IService.cs 文件代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.Text;

using System.ServiceModel;

using System.ServiceModel.Activation;

using System.ServiceModel.Web;

[ServiceContract]

public interface IService

{

[OperationContract]

[WebInvoke(ResponseFormat =

WebMessageFormat.Json, BodyStyle =

WebMessageBodyStyle.Wrapped)]

JsonResult

GetJsonResult(string name, string address, string phone);

}

Service.cs 文件代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

public class Service : IService

{

public

JsonResult GetJsonResult(string name, string address, string

phone)

{

JsonResult result = new JsonResult(name, address, phone);

return result;

}

}

第三步:客户端调用wcf服务,并读取自定义数据类型(在客户端以JSON格式返回)

function

Call() {

$("#divMessagePanel").html("");

var formativeData =

'{"name":"张三","address":"李四","phone":"王五"}';

$.ajax({

type: "post",

url: "../Service.svc/ajaxEndpoint/GetJsonResult",

contentType: "application/json;charset=utf-8",

data: formativeData,

success: function(data) {

alert(data);

var a = eval_r('(' + data +

')'); alert(a.GetJsonResultResult.Name);

$('#divMessagePanel').html("ok");

},

error: function(XMLHttpRequest, textStatus, errorThrown) {

$("#divMessagePanel").html("error");

},

cache: false

});

}

web.config中wcf的配置部分:

name="jsonWcfBehavior">

name="Service">

address="ajaxEndpoint"

behaviorConfiguration="jsonWcfBehavior"

binding="webHttpBinding"

contract="IService">

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值