38 lines
1.4 KiB
C#
38 lines
1.4 KiB
C#
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Linq;
|
|
using System.Reflection;
|
|
|
|
namespace WeatherDashboard
|
|
{
|
|
public class JsonPathConverter : JsonConverter
|
|
{
|
|
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
|
{
|
|
var jsonObject = JObject.Load(reader);
|
|
var target = Activator.CreateInstance(objectType);
|
|
|
|
foreach (PropertyInfo prop in objectType.GetProperties().Where(p => p.CanRead && p.CanWrite))
|
|
{
|
|
var attribute = prop.GetCustomAttribute<JsonPropertyAttribute>(true);
|
|
|
|
var jsonPath = attribute != null ? attribute.PropertyName : prop.Name;
|
|
var token = jsonObject.SelectToken(jsonPath);
|
|
|
|
if (token != null && token.Type != JTokenType.Null)
|
|
{
|
|
object value = token.ToObject(prop.PropertyType, serializer);
|
|
prop.SetValue(target, value, null);
|
|
}
|
|
}
|
|
|
|
return target;
|
|
}
|
|
|
|
// CanConvert is not called when [JsonConverter] attribute is used
|
|
public override bool CanConvert(Type objectType) => false;
|
|
|
|
public override bool CanWrite => false;
|
|
|
|
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
|
|
}
|
|
} |