2016-03-25 60 views
1

我有以下代碼:WCF服務不能識別正確的JSON

[DataContract] 
public class OptimizationServiceSettings 
{ 
    [DataMember] 
    public bool StealthMode { get; set; } 
} 

服務器:

[WebInvoke(Method = "POST", UriTemplate = "SetSettings", BodyStyle = WebMessageBodyStyle.WrappedRequest, 
    ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] 
[OperationContract] 
public void SetSettings(OptimizationServiceSettings settings) 
{ 
    if (settings != null) 
    { 
     _stageOptimizer.ServiceSettings = settings; 
    } 
    else 
    { 
     Trace.TraceError("Attemp to set null OptimizationServiceSettings"); 
    } 
} 

客戶:

private static void SetSettings() 
{ 
    OptimizationServiceSettings op = new OptimizationServiceSettings(); 
    op.StealthMode = true; 

    string jsonInput = ToJson(op); 
    var client = new WebClient(); 
    client.Headers["Content-type"] = "application/json"; 
    client.Encoding = Encoding.UTF8; 
    var response = client.UploadString("http://localhost:8080/BlocksOptimizationServices/SetSettings", "POST", jsonInput); 
} 

private static string ToJson<T>(T data) 
{ 
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); 

    using (MemoryStream ms = new MemoryStream()) 
    { 
     serializer.WriteObject(ms, data); 
     return Encoding.Default.GetString(ms.ToArray()); 
    } 
} 

出於某種原因,SetSettings方法上服務器始終獲得一個空的settings對象。如果我將settings對象類型更改爲string,它將全部有效。我不明白這裏有什麼問題。一切看起來都是正確的。

這裏是jsonInput字符串,我在SetSettings得到了客戶端上的一個例子:被包裹

"{\"StealthMode\":\"true\"}" 
+0

你正在發佈什麼json字符串?你可以在這裏發佈jsonInput變量的值嗎? –

+0

@ PankajKapare新增 –

+1

嘗試發送請求json是這樣的{「settings」:{「StealthMode」:「true」}} –

回答

2

您指定的requestbody:

[WebInvoke(..., BodyStyle = WebMessageBodyStyle.WrappedRequest, ...] 

因此,反序列化纔會成功,如果如@Pankaj建議的那樣,將設置對象包裝在包含對象中。

而不是這樣做,您可以嘗試將屬性更改爲WebMessageBodyStyle.Bare以避免需要包裝參數。