سؤال

I have a method I am using to to work with a Json response. Since this is part of a harness and I am going to be creating a number of different data objects is it possible to make this more generic so I don't have to create same code for each different data object I create.

[DataContract]
class Stats
{
    [DataMember]
    public string StatusCode {get;set;}
    [DataMember]
    public int ProspectCount {get;set;}
    [DataMember]
    public int MessageCount {get;set;}
    [DataMember]
    public int NewListingCount {get;set;}
    [DataMember]
    public int ReminderCount {get;set;}
    [DataMember]
    public int MyListingCount {get;set;}
    [DataMember]
    public int OfficListingCount {get;set;}

}


public static Stats SendRequest(string requestUrl)
{
    try
    {
        HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            if (response.StatusCode != HttpStatusCode.OK)
                throw new Exception(String.Format(
                "Server error (HTTP {0}: {1}).",
                response.StatusCode,
                response.StatusDescription));
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Stats));
            object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
            Stats jsonResponse
            = objResponse as Stats;
            return jsonResponse;
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return null;
    }
}

I essentially want to be able to create a second and third data contract without having to recreate the SendRequest method.

هل كانت مفيدة؟

المحلول 3

I ended up utilizing Json.NET for the serialization piece. This will do everything I needed it to. So now my method looks like:

    public static string ProcessRequest(string requestUrl)
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                string responseContents;
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception(String.Format(
                    "Server error (HTTP {0}: {1}).",
                    response.StatusCode,
                    response.StatusDescription));

                Stream responseStream = response.GetResponseStream();
                using(StreamReader readStream = new StreamReader(responseStream))
                {
                    responseContents = readStream.ReadToEnd();
                }

                return responseContents;
            }


        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
    }

And the serialization component in another method is a simple one liner that takes the response as a string.:

Stats results = JsonConvert.DeserializeObject<Stats>(response);

نصائح أخرى

Two options:

1: Make the SendRequest method the only static method in another class and have every object that needs it call it like this:

RequestSender.SendRequest(requestUrl).

2: Make this and the other classes you have to write extend a superclass that contains the SendRequest(String requestUrl) method so that they have access to that same method via inheritance.

Would a generic method work? The signature might look like this:

public static T SendRequest<T>(string requestUrl) where T : class

In the method body you would replace Stats with T.

Usage:

Stats response = RequestSender.SendRequest<Stats>("some URL");
OtherClass anotherResponse = RequestSender.SendRequest<OtherClass>("some other URL");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top