我正在寻找这种情况的最佳方法:
我想创建WebApi,它将返回给客户端一些对象,例如:
{
id: 1,
name: "name1",
type: "type1"
}
我可以从不同的数据提供程序(文档数据库(检索此类数据,这些提供程序可以具有不同的数据结构,例如:
第一个来源:
{
id: 1,
name: "name1",
type: "type1"
}
第二个来源:
{
productId: 1,
productName: "product",
productType: "type"
}
第三个来源:
{
itemId: 1,
itemName: "name",
itemType: "type"
}
通过下一个数据提供程序轻松扩展的最佳方法是什么?我想补充一点,我一如既往地考虑 JSON.NET 库。所以我相信我正在寻找依赖于数据提供程序的不同 json 映射的示例?任何人都可以帮忙举一些例子吗?让我补充一点,这只是"只读"场景,所以我的意思是 WebApi 调用不同的 dbs =>反序列化为某个对象 =>最终对对象本身进行操作 =>通过 http 发送。
自动映射器和三种不同的dto将是imo最正确的方式。但是如果你想以一种非常简单的方式做到这一点,你可以创建一个具有所有不同属性的类,并让相应的属性使用相同的支持变量
class Item
{
string _id;
public string id
{
get
{
return _id;
}
set
{
_id = value;
}
}
public string productId
{
get
{
return _id;
}
set
{
_id = value;
}
}
public string itemId
{
get
{
return _id;
}
set
{
_id = value;
}
}
string _name;
public string name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public string productName
{
get
{
return _name;
}
set
{
_name = value;
}
}
public string itemName
{
get
{
return _name;
}
set
{
_name = value;
}
}
string _type;
public string type
{
get
{
return _type;
}
set
{
_type = value;
}
}
public string productType
{
get
{
return _type;
}
set
{
_type = value;
}
}
public string itemType
{
get
{
return _type;
}
set
{
_type = value;
}
}
}
另一种可能的方法是将序列化设置与重写 ResolvePropertyName 方法的自定义协定解析程序对象一起使用。
您可以使用自动映射器来解决此问题。
http://automapper.org/
https://github.com/AutoMapper/AutoMapper/wiki/Getting-started
尝试下面的示例
public class ReturnObject
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
public class Source1
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
public class Source2
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public string ProductType { get; set; }
}
public class Source3
{
public int ItemId { get; set; }
public string ItemName { get; set; }
public string ItemType { get; set; }
}
自动映射器配置文件
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
//Same properties
CreateMap<Source1, ReturnObject>();
//Difference properties
CreateMap<Source2, ReturnObject>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(f => f.ProductId))
.ForMember(dest => dest.Name, opt => opt.MapFrom(f => f.ProductName))
.ForMember(dest => dest.Type, opt => opt.MapFrom(f => f.ProductType));
CreateMap<Source3, ReturnObject>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(f => f.ItemId))
.ForMember(dest => dest.Name, opt => opt.MapFrom(f => f.ItemName))
.ForMember(dest => dest.Type, opt => opt.MapFrom(f => f.ItemType));
}
}