简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM