JSON到动态对象与强类型对象 [英] JSON to Dynamic Object vs. Strongly Typed Object

查看:108
本文介绍了JSON到动态对象与强类型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定是否没有大图,还是只是错过了什么,但是将JSON-String解析为动态对象有什么好处?

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?

如果我有这样的课程

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

然后我使用HttpClient获取这样的对象

and I use the HttpClient to get the object like this

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

此代码有什么好处?

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?

推荐答案

相对于动态(性能\便利),您将始终更喜欢使用强类型.

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. 当您想解析xml并且不想使用XElement,XPath等时.

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

COM互操作-它使事情变得非常简单和好用(尝试使用Excel \ Word,您将被说服).

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

在某些情况下,使用动态方式而不是反射方式会更好,更易读.

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

这篇关于JSON到动态对象与强类型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆