[英]An efficient way to convert JObject to class with Automapper (C#)
I need to convert JSON to a custom object, I'm using AutoMapper to do it.我需要将 JSON 转换为自定义 object,我正在使用 AutoMapper 来执行此操作。 This is my code and it currently works:这是我的代码,它目前有效:
public string json = @"
{
'index': 'dagger',
'name': 'Dagger',
'equipment_category': 'weapon'
}"
public class Equipment
{
public string Index { get; set; }
public string Name { get; set; }
public string EquipmentCategory { get; set; }
}
public Equipment Convert()
{
var config = new MapperConfiguration(config =>
{
config.CreateMap<JObject, Equipment>()
.ForMember(dest => dest.Index, opt => opt.MapFrom(src => src["index"])
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src["name"])
.ForMember(dest => dest.EquipmentCategory, opt => opt.MapFrom(src => src["equipment_category"])
}
var mapper = config.CreateMapper();
var result = mapper.Map<Equipment>(JObject.Parse(json));
return result;
}
The downside of this is that I have to create a ForMember
rule for every property in the object.这样做的缺点是我必须为 object 中的每个属性创建一个ForMember
规则。 Does anyone know of a more efficient way of doing this?有谁知道这样做更有效的方法?
You don't need Automapper to convert the json to a POCO (Equipment class).您不需要 Automapper 将 json 转换为 POCO(设备类)。 Use JsonConvert.DeserializeObject<T>(json)
along with JsonPropertyAttribute
.将JsonConvert.DeserializeObject<T>(json)
与JsonPropertyAttribute
一起使用。 The "mapping" will be taken care for you using the Newtonsoft deserializer.使用 Newtonsoft 反序列化器会为您处理“映射”。
public class Equipment
{
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("equipment_category")]
public string EquipmentCategory { get; set; }
}
Deserialize to POCO反序列化为 POCO
string json = @"
{
'index': 'dagger',
'name': 'Dagger',
'equipment_category': 'weapon'
}"
var equipment = JsonConvert.DeserializeObject<Equipment>(json);
Once you have a POCO instance, Automapper becomes handy to map this class to another POCO.一旦有了 POCO 实例,Automapper 就可以方便地使用 map 这个 class 到另一个 POCO。
var result = mapper.Map<EquipmentDto>(equipment);
Newtonsoft Serializing and Deserializing JSON https://www.newtonsoft.com/json/help/html/SerializingJSON.htm Newtonsoft 序列化和反序列化 JSON https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.