2014-01-08 106 views
0

我想從WCF服務返回JSONified匿名類型。從匿名類型返回Json

我已經這樣做是成功的,但是我正在尋找一個更好的選擇..

// In IService 
[OperationContract] 
[FaultContract(typeof(ProcessExecutionFault))] 
[Description("Return All Room Types")] 
[WebInvoke(UriTemplate = "/GetAllRoomTypes", Method = "GET", RequestFormat = WebMessageFormat.Json, 
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] 
Stream GetAllRoomTypes(); 

// In Service Implementation 

[LogBeforeAfter] 
Stream GetAllRoomTypes() 
{ 
    try 
    { 
     var allRoomTypes = Helper.GetAllRoomTypes(); 
     var stream = new MemoryStream(); 
     var writer = new StreamWriter(stream); 
     writer.Write(allRoomTypes); 
     writer.Flush(); 
     stream.Position = 0; 
     return stream; 
    } 
    catch (Exception ex) 
    { 
     TableLogger.InsertExceptionMessage(ex); 
     return null; 
    } 
} 

// In Business Logic: 

public string GetAllRoomTypes(){ 
    try 
    { 
     return CustomRetryPolicy.GetRetryPolicy().ExecuteAction(() => 
     { 
      using (var context = new DatabaseEntity()) 
      { 
      var retResult = from v in context.RoomMasters select new { Id = v.RoomTypeID, Type = v.RoomType }; 
      var retResult1 = retResult.ToJson(); 
      return retResult1; 
      } 
      } 
     ); 
     } 
     catch (Exception ex) 
     { 
     Trace.Write(String.Format("Exception Occured, Message: {0}, Stack Trace :{1} ", ex.Message, ex.StackTrace)); 
     return null; 
     } 
} 

我的問題是,是否有更好的方法來做到這一點?

+0

約重新調諧[信息](http://msdn.microsoft.com/en-us/library/ms734675(V = vs.110)什麼。 aspx),我在[Nelibur](https://github.com/Nelibur/Nibibur)中也是這樣做的。 Here're [Service](https://github.com/Nelibur/Nelibur/wiki/How-to-create-REST-message-based-Servcie-on-pure-WCF)和[Client](https:// github.com/Nelibur/Nelibur/wiki/How-to-create-REST-message-based-Client-on-pure-WCF) – GSerjo

回答

0

嘗試使用JavaScriptSerializer

using (var context = new DatabaseEntity()) 
{ 
    var retResult = from v in context.RoomMasters select new { Id = v.RoomTypeID, Type = v.RoomType }; 
    JavaScriptSerializer serializer = new JavaScriptSerializer(); 
    var output = serializer.Serialize(retResult);  
    return output; 
} 
+0

我已經使用了擴展方法ToJson,使用Newtonsoft將對象轉換爲json –

+0

有沒有在WCF中實現此功能的更好方法? WCF中的 –

+0

您還可以使用[DataContractJsonSerializer](http://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.json.datacontractjsonserializer.aspx)類 – chridam

0

使用類作爲您的數據契約,而不是直接返回JSON。然後,在您的方法中,只需返回數據合同類的列表或數組。 WCF將負責將其序列化爲配置的格式(JSON或XML)。

[DataContract] 
public class RommDto{ 
    [DataMember] 
    public int Id {get; set;} 
    [DataMember] 
    public RoomType Type {get; set;} 
} 

.....

[LogBeforeAfter] 
RoomDto[] GetAllRoomTypes() 
{ 
.... 
} 
+0

,但它會要求我創建這樣的爲每種類型..任何其他更好的方式? –