简体   繁体   English

处理从Web服务器收到的json的优雅方式?

[英]Elegant way to handle json received from web server?

What way is better in C# to handle json received from web server? 在C#中处理从Web服务器收到的json更好的方法是什么?

Is it okay to pass System.Json.JsonValue object directly to response handler? 是否可以将System.Json.JsonValue对象直接传递给响应处理程序?

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? 或者我需要用Json实现一些“Response”接口来包装JsonValue?

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? 或者在将json传递给处理程序之前将其转换为众所周知的对象?

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 . 如果时间不受限制 - 我建议使用IResponseIResponseConverter ,坚持使用更灵活的解决方案,分担责任和担忧。

If time is limited I would suggest to stick with IResponseConverter so you would be able to add support of new data formats easily. 如果时间有限,我建议坚持使用IResponseConverter这样您就可以轻松添加对新数据格式的支持。

MVC has System.Web.Mvc.JsonResult which might be worth a look. MVC有System.Web.Mvc.JsonResult,值得一看。

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 这里有一个很好的总结和一种与我使用过的技术非常相似的技术: http//www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse- json.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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