反序列化JSON不同文件相同的对象结构
问题描述:
我在寻找这样的情况下,最好的办法:反序列化JSON不同文件相同的对象结构
我想创建的WebAPI返回给客户端的一些对象,如:
{
id: 1,
name: "name1",
type: "type1"
}
我可以检索从其可具有不同的数据结构等的不同数据提供者(文件DBS)这样的数据:
第一源:
{
id: 1,
name: "name1",
type: "type1"
}
第二个来源:
{
productId: 1,
productName: "product",
productType: "type"
}
第三个来源:
{
itemId: 1,
itemName: "name",
itemType: "type"
}
什么将是可以很容易地与未来数据提供扩展的最佳方法?我想补充一点,我一直在考虑JSON.NET库。所以我相信我正在寻找取决于数据提供者的不同json映射的示例?任何人都可以帮助一些例子?我还要补充说它只是'只读'场景,所以我的意思是WebApi调用不同的dbs =>反序列化到某个对象=>最终操纵对象本身=>通过http发送。
答
Automapper和三个不同的dtos将是最正确的方式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;
}
}
}
答
您可以使用AutoMapper解决此问题。
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; }
}
AutoMapper档案
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));
}
}
+0
所以事情是我想避免定义那些'SourceX'实体。而不是直接从documentdb到ReturnObject的反序列化 –
我会简单地使用来自各供应商的结果映射到自己的可重复使用的映射,甚至如果数据看起来相似。任何通用的,你将尝试使下一个新的提供商必然打破。 – oerkelens
最好考虑做的事情是IMO使用[AutoMapper](http://automapper.org/) –