使用Json.Net反序列化嵌套属性,而不使用数据注释



我有一个从多个API获取数据的应用程序。为了尽量减少类的数量,我需要映射到每个属性。我已经实现了一个简单的json.netContractResolver。然而,当我试图将一个属性映射到子属性时,我遇到了一些麻烦。

JSON格式1:

{
"event_id": 123,
"event_name": "event1",
"start_date": "2018-11-30",
"end_date": "2018-12-04",
"participants": {
"guests": [
{
"guest_id": 143,
"first_name": "John",
"last_name": "Smith",               
},
{
"guest_id": 189,
"first_name": "Bob",
"last_name": "Duke",    
}
]
}
}

JSON格式2:

{
"name": "event2",
"from": "2017-05-05",
"to": "2017-05-09",
"city":"Some other city",
"country":"US",
"guests": [
{
"email":"jane@smith.com",
"firstName":"Jane",
"lastName":"Smith",
"telephone":"1-369-81891"
}
],
}

以下是我的模型类:

public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public List<Guest> Guests { get; set; }
}
public class Guest
{
public string GuestId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }       
}

还有我的解析器:

public class EventResolver : DefaultContractResolver
{
private Dictionary<string,string> PropertyMappings { get; set; }
public EventResolver()
{
this.PropertyMappings = new Dictionary<string, string>
{
{"EventId", "event_id"},
{"StartDate", "start_date" },
{"EndDate", "end_date" },
{"EventName", "event_name" },
{"Guests", "participants.guests"}
};
}
protected override JsonContract CreateContract(Type objectType)
{
return base.CreateContract(objectType);
}
protected override string ResolvePropertyName(string propertyName)
{
var resolved = this.PropertyMappings.TryGetValue(propertyName, out var resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}

我知道用路径代替属性名是行不通的。怎么会这样呢?

我认为解析器的想法不会奏效,因为您要重新映射的不仅仅是属性名——您还试图反序列化为一个并不总是与JSON形状匹配的类结构。此工作更适合一组JsonConverters。

以下是基本方法:

  1. 为JSON不同的每个模型类创建一个JsonConverter
  2. ReadJson方法内部,从读取器加载一个JObject
  3. 通过查找始终存在于该格式的众所周知的属性名称来检测您的格式。例如,如果您可以依赖于event_id始终以第一种格式存在,那么这是检测它的好方法,因为您知道第二种格式不具有该属性。如果需要,您可以根据是否存在多个属性进行检查;关键是要使用一些只以一种格式出现而不以其他格式出现的组合。(或者,如果您提前知道需要哪种格式,您可以简单地对转换器进行参数化,即在构造函数中传递一个格式标志。(
  4. 一旦知道了格式,就从JObject中填充模型

对于问题中显示的Event模型,转换器可能看起来像这样:

public class EventConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Event);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Event evt = new Event();
JObject obj = JObject.Load(reader);
if (obj["event_id"] != null)
{
// JSON format #1
evt.EventId = (int)obj["event_id"];
evt.EventName = (string)obj["event_name"];
evt.StartDate = (DateTime)obj["start_date"];
evt.EndDate = (DateTime)obj["end_date"];
evt.Guests = obj.SelectToken("participants.guests").ToObject<List<Guest>>(serializer);
}
else if (obj["name"] != null)
{
// JSON format #2
evt.EventName = (string)obj["name"];
evt.StartDate = (DateTime)obj["from"];
evt.EndDate = (DateTime)obj["to"];
evt.Guests = obj["guests"].ToObject<List<Guest>>(serializer);
}
else
{
throw new JsonException("Unknown format for Event");
}
return evt;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

类似地,对于Guest模型,我们可能有这个JsonConverter:

public class GuestConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Guest);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Guest guest = new Guest();
JObject obj = JObject.Load(reader);
if (obj["guest_id"] != null)
{
// JSON format #1
guest.GuestId = (string)obj["guest_id"];
guest.FirstName = (string)obj["first_name"];
guest.LastName = (string)obj["last_name"];
}
else if (obj["email"] != null)
{
// JSON format #2
guest.FirstName = (string)obj["firstName"];
guest.LastName = (string)obj["lastName"];
guest.Email = (string)obj["email"];
}
else
{
throw new JsonException("Unknown format for Guest");
}
return guest;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

要使用转换器,请将它们添加到JsonSerializerSettings对象的Converters集合中,并将设置传递给DeserializeObject(),如下所示:

var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new EventConverter(), new GuestConverter() }
};
var evt = JsonConvert.DeserializeObject<Event>(json, settings);

演示小提琴:https://dotnetfiddle.net/KI82KB

当你需要支持越来越多的格式和生产者时,我认为你对它的设计太过了,它会变得一团糟。想象一下,如果你有15个不同格式的事件制作人,你的解析器会是什么样子?

您需要的是为您的域创建一组适合您的域和需求的类。

public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public List<Guest> Guests { get; set; }
}
public class Guest
{
public string GuestId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }       
}
public interface IEventProvider
{
Event[] GetEvents();
}

然后为每个外部生产者创建一组类,并将其映射到您的域类,例如使用AutoMapper配置文件或手动。

namespace YourCompany.EventProvider.Api1
{
// just an example with json2sharp, use data annotations if you want
public class Guest
{
public int guest_id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
}
public class Participants
{
public List<Guest> guests { get; set; }
}
public class RootObject
{
public int event_id { get; set; }
public string event_name { get; set; }
public string start_date { get; set; }
public string end_date { get; set; }
public Participants participants { get; set; }
}
public class Api1EventProvider : IEventProvider
{
public Event[] GetEvents()
{
RootObject[] api1Response = GetFromApi();
return _mapper.Map<RootObject[], Event[]>(api1Response);
}
}       
}

是的,我会上更多的课。但这段代码会更好,可读性更强,可维护性更强;与创建解析器相比,您将花费更少的时间来创建它;未来的开发人员不会在每次生产者改变API时哭泣
代码质量不是要创建更少的类。

相关内容

  • 没有找到相关文章

最新更新