如何向/与RESTful WCF服务传递和使用JSON参数?

我是RESTful服务的初学者。

我需要创建一个接口,客户端需要传递最多9个参数。

我宁愿将参数作为JSON对象传递。

例如,如果我的JSON是:

'{ "age":100, "name":"foo", "messages":["msg 1","msg 2","msg 3"], "favoriteColor" : "blue", "petName" : "Godzilla", "IQ" : "QuiteLow" }' 

如果我需要在下面执行下面的服务器端方法:

 public Person FindPerson(Peron lookUpPerson) { Person found = null; // Implementation that finds the Person and sets 'found' return found; } 

问题(S):
我应该如何使用上面的JSON字符串从客户端进行调用? 我如何创建RESTful服务方法的签名和实现

  • 接受这个JSON,
  • 将它解析并反序列化为Person对象和
  • 调用/将FindPerson方法的返回值返回给客户端?

如果要创建WCF操作以接收该JSON输入,则需要定义映射到该输入的数据协定。 有一些工具会自动执行此操作,包括我在http://jsontodatacontract.azurewebsites.net/上写过的一些工具(有关此工具是如何在此博客文章中编写的更多详细信息)。 该工具生成了这个类,您可以使用它:

 // Type created for JSON at <> [System.Runtime.Serialization.DataContractAttribute()] public partial class Person { [System.Runtime.Serialization.DataMemberAttribute()] public int age; [System.Runtime.Serialization.DataMemberAttribute()] public string name; [System.Runtime.Serialization.DataMemberAttribute()] public string[] messages; [System.Runtime.Serialization.DataMemberAttribute()] public string favoriteColor; [System.Runtime.Serialization.DataMemberAttribute()] public string petName; [System.Runtime.Serialization.DataMemberAttribute()] public string IQ; } 

接下来,您需要定义一个操作合同来接收它。 由于JSON需要进入请求的主体,因此最自然的HTTP方法是POST ,因此您可以按如下方式定义操作:方法为“POST”,样式为“Bare”(这意味着您的JSON直接映射到参数)。 请注意,您甚至可以省略MethodBodyStyle属性,因为"POST"WebMessageBodyStyle.Bare分别是它们的默认值。

 [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)] public Person FindPerson(Peron lookUpPerson) { Person found = null; // Implementation that finds the Person and sets 'found' return found; } 

现在,在该方法中,您将输入映射到lookupPerson 。 如何实现方法的逻辑由您决定。

评论后更新

可以在下面找到使用JavaScript(通过jQuery)调用服务的一个示例。

 var input = '{ "age":100, "name":"foo", "messages":["msg 1","msg 2","msg 3"], "favoriteColor" : "blue", "petName" : "Godzilla", "IQ" : "QuiteLow" }'; var endpointAddress = "http://your.server.com/app/service.svc"; var url = endpointAddress + "/FindPerson"; $.ajax({ type: 'POST', url: url, contentType: 'application/json', data: input, success: function(result) { alert(JSON.stringify(result)); } }); 

1 – 添加WebGet属性

  _  _ Public Function YourFunch(inpt As String) As String 

2 – 使用NewtonSoft将json序列化/反序列化为您的对象(注意上面只接受String),NewtonSoft比MS序列化器快得多。

使用NewtonSoft进行序列化http://json.codeplex.com/

3-你的.svc文件将包含Factory =“System.ServiceModel.Activation.WebServiceHostFactory

4-你的web.config将包含

         

…和…