开发者

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.JsonV开发者_运维百科alue 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);
    });


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜