C# 从匿名类型返回Json

C# 从匿名类型返回Json,c#,json,wcf,rest,anonymous-types,C#,Json,Wcf,Rest,Anonymous Types,我试图从WCF服务返回JSONified匿名类型 我成功地做到了这一点,但我正在寻找更好的选择 // In IService [OperationContract] [FaultContract(typeof(ProcessExecutionFault))] [Description("Return All Room Types")] [WebInvoke(UriTemplate = "/GetAllRoomTypes", Method = "GET", RequestFormat = WebM

我试图从WCF服务返回JSONified匿名类型

我成功地做到了这一点,但我正在寻找更好的选择

// 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;
      }
 }

我的问题是,有更好的方法吗?

尝试使用
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;
}

使用类作为数据协定,而不是直接返回json。然后,在方法中,只返回数据协定类的列表或数组。WCF将负责将其序列化为配置的格式(JSON或XML)


我使用了一个扩展方法ToJson,该方法使用newtonsoft将对象转换为json。有没有更好的方法在WCF中实现此功能?在WCF中,您也可以使用类,但需要我为每种类型创建类。。还有其他更好的方法吗?那重新调谐呢,我也是这么做的。这是和
[DataContract]
public class RommDto{
    [DataMember]
    public int Id {get; set;}
    [DataMember]
    public RoomType Type {get; set;}
}
[LogBeforeAfter]
RoomDto[] GetAllRoomTypes()
{
....
}