Ilya Golota
Ilya Golota

Reputation: 51

Elegant way to handle json received from web server?

What way is better in C# to handle json received from web server?

Is it okay to pass System.Json.JsonValue object directly to response handler?

new FooWebService().FetchSomethingAsync(12, "bar", json =>
    {
        DoSomething1(ConvertJsonToClass1(json["key1"]));
        DoSomething2(ConvertJsonToClass2(json["key2"]));
    });

Or I need wrap JsonValue with json implementation of some “Response” interface?

interface IResponse
{ ... }

class JsonResponse : IResponse
{ ... }

new FooWebService().FetchSomethingAsync(12, "bar", response =>
    {
        DoSomething1(ConvertResponseToClass1(response["key1"]));
        DoSomething2(ConvertResponseToClass2(response["key2"]));
    });

Or convert json into well known objects before passing it to handler?

interface IResponseConverter
{ ... }

class JsonConverter : IResponseConverter
{ ... }

var service = new FooWebService() 
{
    ResponseConverter = new JsonConverter()
};
service.FetchSomethingAsync(12, "bar", response =>
    {
        DoSomething1(response.Key1);
        DoSomething2(response.Key2);
    });

Upvotes: 0

Views: 283

Answers (2)

Brian Kretzler
Brian Kretzler

Reputation: 9938

MVC has System.Web.Mvc.JsonResult which might be worth a look.

Have you consider using a dynamic type? Here's a good summary and a technique very similar to one I've used: http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx

Upvotes: 1

sll
sll

Reputation: 62544

It depends on how much flexibility you want to have and on other hand how many time you have to implement a complete solution.

If time is not limited - I would suggest to stick with more flexible solution with separated responsibilities and concerns using both IResponse and IResponseConverter.

If time is limited I would suggest to stick with IResponseConverter so you would be able to add support of new data formats easily.

Upvotes: 1

Related Questions