如果您想创建一个 WCF 操作来接收该 JSON 输入,您需要定义一个映射到该输入的数据协定。有一些工具可以自动执行此操作,包括我不久前在http://jsontodatacontract.azurewebsites.net/ 写的一个(有关此工具如何编写的更多详细信息,请参见this blog post)。该工具生成了这个类,您可以使用它:
// Type created for JSON at <<root>>
[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 直接映射到参数)。请注意,您甚至可以省略 Method 和 BodyStyle 属性,因为 "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));
}
});