2013-07-17 88 views
1

所以可以說我有一個Json數據集如下,即使這個數據的JSON數據(模型或結構)不是靜態的,它會根據每個調用而改變,我如何將一個通用的Json數據集傳遞給WCF代碼的POST方法?如何將動態Json對象(數據)傳遞給wcf ResTful服務?

{ 
    "experience": 14746, 
    "status": true, 
    "name": "Aaron", 
    "uuid": "3123" 
} 

我想從正文使用POSTMAN或SoapUI?

public object PostData(string id, [FromBody] JObject data) 
{ 
//Do Something with data 
} 


public interface IPostService 
{ 
    [OperationContract(Name = "PostData")] 
    [WebInvoke(Method = "POST", UriTemplate = "/PostData?id={id}&data={data}")] 
    object PostData(string id,[FromBody] JObject data); 

} 

任何幫助,將不勝感激

回答

1

當您在UriTemplate指定屬性的變量數據你說值成爲查詢字符串,而不是在BODY,默認的HTTP方法WebInvokeMethod屬性爲POST。

public object PostData(string id, string data) 
{ 
    //Do Something with data 
} 


public interface IPostService 
{ 
    [OperationContract(Name = "PostData")] 
    [WebInvoke(UriTemplate = "/PostData?id={id})] 
    object PostData(string id, string data); 
} 

然後,您可以使用Newtonsoft庫將格式爲Json的字符串值解析爲具有動態屬性的對象。您可以使用帶有Nuget的Newtonsoft庫。

要了解如何使用Newtonsoft解析動態對象,請點擊here

+0

請您提供的說明,我怎麼能叫郵差用或SOAPUI這項服務? – user1429595

+0

你是否指用POSTMAN或SOAPUI調用SOAP服務? – Joseph

+0

以及它是WCF休息服務!不是有可能嗎? – user1429595

1

補充我以前的答案。在反序列化對象時,Newtonsoft可以與動態一起使用。以這種方式執行。

var results = JsonConvert.DeserializeObject<dynamic>(json); 
var experience= results.Experience; 
var status= results.Status; 
var name= results.Name; 
var uuid= results.Uuid; 
var dynamic_property= results.AnotherProperty; 

的另一種方式。如果你知道要解析的類的所有可能屬性。您可以使用Newtonsoft.Json的JsonProperty屬性,並使用強類型的DeserializeObject。

public class MyModel 
{ 
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public int experience {get;set;} 

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public bool status {get;set;} 

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public string name {get;set;} 

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public string uuid {get;set;} 

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public object property_1 {get;set;} 

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
    public object property_2 {get;set;} 

    ... 
} 

你可以提出一個要求:

var httpRequest = WebRequest.Create(string.Format("baseurl" + "/PostData?id={0}", id)); 
httpRequest.Method = "POST"; 
httpRequest.ContentType = "application/json"; 
httpRequest.ContentLength = data.Length; 

try 
{ 
    using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream())) 
    { 
     if (!string.IsNullOrEmpty(data)) 
     { 
      streamWriter.Write(data); 
      streamWriter.Flush(); 
      streamWriter.Close(); 
     } 
    } 

    var response = httpRequest.GetResponse(); 
} 
catch (Exception) 
{} 
+0

我的問題不是反序列化,我知道怎麼做那個部分,問題是如何先傳遞這個信息,我有兩個參數(id和data)對不對? 「數據」是一個巨大的字符串,我不希望tp傳遞數據作爲URL中的參數,我需要從消息BODY傳遞數據,但我不知道如何執行此操作或將內容類型設置爲,謝謝 – user1429595

+0

如果您使用C#,則有答案。 – Joseph

相關問題