Веб-клиент WCF API Чистый Json: вызовет ли использование MemoryStream перформанс Performace при использовании в вызове API для большого объема данных - PullRequest
0 голосов
/ 22 февраля 2012

Я написал следующий код для возврата другого объекта Json, основанного на передаче пользователя JobId. я хотел знать, было ли использование MemoryStream в функции ReturnPureJson вызывать какую-либо проблему, связанную с производительностью, в вызовах API WCF?

    [WebInvoke(UriTemplate = "{jobId}", Method = "GET", ResponseFormat = WebMessageFormat.Json)]
    public Stream GetJobData(Guid jobId)
    {

        object responseData = null;

        //Code to fetch the proper Job Based on the JobId Passed
        Job job = GetJobData(jobId);

        if (job != null)
        {
            switch (job.JobType)
            {
                case JobType.UserData:
                    responseData = GetUserData(); //Returns a List<UserData> where Userdata is a class
                    break;
                case Job.EJobType.ApplicationData:
                     responseData = GetApplicationData();//Returns a List<ApplicationData> where ApplicationData is a class
                    break;
                  //some more case statements to fetch appropriate response
            }
        }

        return ReturnPureJson(responseData);
    }
    private Stream ReturnPureJson(dynamic responseModel)
    {
        string jsonClient = Json.Encode(responseModel);
        WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
        return new MemoryStream(Encoding.UTF8.GetBytes(jsonClient));
    }

1 Ответ

0 голосов
/ 22 февраля 2012

Почему вы используете MemoryStream? Почему бы просто не вернуть JSON в виде строки ....

Imports System.IO
Imports System.Runtime.Serialization.Json

Public Class JsonConvertor(Of t)
    Public Function FromJSON(ByRef sreader As StreamReader) As t
       If GetType(t).Equals(GetType(String)) Then
           Dim result As Object = sreader.ReadToEnd.Replace("""", "")
           Return CType(result, t)
       Else
           Dim ds As New DataContractJsonSerializer(GetType(t))
           Dim result As t = DirectCast(ds.ReadObject(sreader.BaseStream), t)
           ds = Nothing
           Return result
       End If
   End Function

   Public Function ToJSON(ByVal ObjectToBeConverted As t) As String
       Dim s As Stream = New MemoryStream()
       Dim ds As New DataContractJsonSerializer(GetType(t))
       ds.WriteObject(s, ObjectToBeConverted)

       Dim output As New StreamReader(s)
       Dim ostr As String = output.ReadToEnd
       s.Dispose()
       Return ostr
   End Function
End Class

Это позволит вам преобразовать любой «DataContract» в или из JSON.

...