JSON to Dynamic Object vs. Strongly Typed Object

我与影子孤独终老i 提交于 2019-12-08 08:14:36

问题


I'm not sure if I don't get the big picture or if I just miss something but what are the benefits of parsing a JSON-String to a dynamic object?

If I have a class like this

class Product
{
    public string Name { get; set; }
    public double Price { get; set; }
    public string Category { get; set; }
}

and I use the HttpClient to get the object like this

Product product = await response.Content.ReadAsAsync<Product>();

What do I benefit from this code?

string content = await response.Content.ReadAsStringAsync();
dynamic product = JObject.Parse(content);

If I want to use them I need to write

product.Name

With the strongly typed apporach I at least have the intellisense. If the service changes the Product the dynamic approach doesn't help me either because I still need to access it like I mentioned above.

So what am I missing? Why should I use dynamics or when?


回答1:


You will always prefer to use a strong type over a dynamic (performance\convenience).

Here are some cases you would like to use a dynamic:

  1. When you want to parse an xml and dont want to work with XElement's, XPath's etc.

  2. COM interop - It makes things really easy and nice (try working with Excel\Word and you will be convinced).

  3. In some cases it's nicer and readable to use a dynamic instead of reflection.



来源:https://stackoverflow.com/questions/31118624/json-to-dynamic-object-vs-strongly-typed-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!