简体   繁体   English

将动态对象字段与强类型模型一起使用

[英]Using dynamic object fields with a strongly typed model

I am currently working with a nuget google geocoding api that returns a object with dynamic fields( specifically this one ). 我目前正在使用nuget google地理编码api,该api返回具有动态字段的对象( 特别是此对象)。 Based on the input address, the return object often returns different fields. 根据输入地址,返回对象通常返回不同的字段。 Is there an efficient manner in which i can go through the dynamic fields and match them up to my model without 100 if blocks? 有没有一种有效的方式,我可以遍历动态字段并将其与我的模型匹配,而无需100个if块?

Example: Input: New York, NY 示例:输入:纽约州纽约市

returns: 收益: 在此处输入图片说明

or Input: 1600 West Pennsylvania Avenue 或输入:1600 West Pennsylvania Avenue

returns: 收益: 在此处输入图片说明

Model: 模型:

        public string streetnumber { get; set; }
        public string route { get; set; }
        public string city { get; set; }
        public string postalcode { get; set; }
        public string state { get; set; }
        public string country { get; set; }

You can install the package AutoMapper available in Nuget Gallery. 您可以安装Nuget Gallery中提供的软件包AutoMapper。

To install, open the Console Package Manager, select the project that you want to install the package and type: Install-Package AutoMapper 要安装,请打开控制台软件包管理器,选择要安装软件包的项目,然后键入:Install-Package AutoMapper

After that, you can use the method Mapper.DynamicMap to map objects from Geocoding API. 之后,您可以使用Mapper.DynamicMap方法来映射来自Geocoding API的对象。

Below an example to clarify: 下面以一个例子来说明:

var order = new {CustomerName = "Bob Smith"};
var message = Mapper.DynamicMap<ICreateOrderMessage>(order);
message.CustomerName.ShouldEqual("Bob Smith");

If you have any doubt about the library, check out on http://automapper.org/ 如果您对该库有任何疑问,请访问http://automapper.org/

I hope it helps you. 希望对您有帮助。 ;) ;)

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

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