2013-10-12 97 views
5

我正在嘗試在接受JSON列表的dotnet(VS 2012)中創建一個寧靜的Web服務。有這個非常有用的帖子。將JSON數組發佈到WCF Rest服務結果的空參數中。 DataContract?

Jquery Ajax Posting json to webservice

的例子是發現,但我需要的DataContract排序。這裏是我的問題:

提琴手帖子:

{ "Markers": [ 
{ "position": "128.3657142857143", "markerPosition": "7" }, 
{ "position": "235.1944023323615", "markerPosition": "19" }, 
{ "position": "42.5978231292517", "markerPosition": "-3" } 
]}; 

在VS2012調試我看到了等價的:

{ "Markers": [ 
{ "position": "0", "markerPosition": "0" }, 
{ "position": "0", "markerPosition": "0" }, 
{ "position": "0", "markerPosition": "0" } 
]}; 

下面是代碼(直接從鏈接的例子):

public class Marker 
{ 
    decimal position { get; set; } 
    int markerPosition { get; set; } 
} 

public string CreateMarkers(List<Marker> Markers) 
{ 
    return "Received " + Markers.Count + " markers."; 
} 

這裏是合同:

[OperationContract] 
[WebInvoke(UriTemplate = "Markers", Method = "POST", ResponseFormat = WebMessageFormat.Json, 
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] 
string CreateMarkers(List<Marker> Markers); 

這等,同樣精彩,後解釋說,datacontract需要設置才能看到參數值:

WCF REST POST of JSON: Parameter is empty

我原來的問題是應該的數據合同是什麼。我開始於:

[OperationContract] 
[WebInvoke(UriTemplate = "Markers", Method = "POST", ResponseFormat =   WebMessageFormat.Json, 
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] 
string CreateMarkers(List<Marker> Markers); 

之後消息結構通過,但空的內容。然後,根據建議,我嘗試過:

[OperationContract] 
[WebInvoke(UriTemplate = "Markers", Method = "POST", ResponseFormat =   WebMessageFormat.Json, 
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] 
string CreateMarkers(List<Marker> Markers); 

之後的消息結構和內容爲空。

[OperationContract] 
    [WebInvoke(UriTemplate = "WrappedMarkers", Method = "POST", ResponseFormat = WebMessageFormat.Json, 
     RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] 
    string WrappedMarkers(MarkerRequest wrappedmarkers); 

[DataContract] 
    public class MarkerRequest 
    { 
    [DataMember] 
    public List<Marker> Markers 
    { 
     get { return _markers; } 
     set { _markers = value; } 
    } 

    private List<Marker> _markers = new List<Marker>(); 
} 


public string WrappedMarkers(MarkerRequest wrappedmarkers) 
    { 
     return wrappedmarkers.Markers.ToString(); 
    } 

這裏是操作簡約,改爲WrappedRequest

結構是正確的,但內容又被空。

回到原點。我似乎能夠看到消息的結構。我如何獲得映射到結構的內容?

回答

8

與參數我所知,你得「0」的價值,因爲你沒有設置[DataContract][數據成員]屬性上的數據類。加入這些屬性後,你的班級應該看起來像

[DataContract] 
public class Marker 
{ 
    [DataMember] 
    decimal position { get; set; } 
    [DataMember] 
    int markerPosition { get; set; } 
} 
+0

是的。這解決了這個問題。立即。謝謝! –