如果要创建WCF操作以接收该JSON输入,则需要定义映射到该输入的数据协定.有一些工具会自动执行此操作,包括我在
http://jsontodatacontract.azurewebsites.net/回写的一个工具(有关此工具是如何在
this blog post编写的更多详细信息).该工具生成了这个类,您可以使用它:
// 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直接映射到参数).请注意,您甚至可以省略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));
}
});