【发布时间】:2025-12-15 19:15:01
【问题描述】:
我正在尝试使用 this answer 到 Can I specify a path in an attribute to map a property in my class to a child property in my JSON? 的 JsonConverter Brian Rogers 将 JSON 中的嵌套属性映射到平面对象。
转换器运行良好,但我需要触发 OnDeserialized 回调来填充其他属性,但它没有被触发。如果我不使用转换器,则会触发回调。
例子:
string json = @"{
'response': {
'code': '000',
'description': 'Response success',
},
'employee': {
'name': 'Test',
'surname': 'Testing',
'work': 'At office'
}
}";
// employee.cs
public class Employee*
{
[JsonProperty("response.code")]
public string CodeResponse { get; set; }
[JsonProperty("employee.name")]
public string Name { get; set; }
[JsonProperty("employee.surname")]
public string Surname { get; set; }
[JsonProperty("employee.work")]
public string Workplace { get; set; }
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
Workplace = "At Home!!";
}
}
// employeeConverter.cs
public class EmployeeConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
object targetObj = Activator.CreateInstance(objectType);
foreach (PropertyInfo prop in objectType.GetProperties()
.Where(p => p.CanRead && p.CanWrite))
{
JsonPropertyAttribute att = prop.GetCustomAttributes(true)
.OfType<JsonPropertyAttribute>()
.FirstOrDefault();
string jsonPath = (att != null ? att.PropertyName : prop.Name);
JToken token = jo.SelectToken(jsonPath);
if (token != null && token.Type != JTokenType.Null)
{
object value = token.ToObject(prop.PropertyType, serializer);
prop.SetValue(targetObj, value, null);
}
}
return targetObj;
}
public override bool CanConvert(Type objectType)
{
// CanConvert is not called when [JsonConverter] attribute is used
return false;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
如果我在获得的 Employee 类中添加[JsonConverter(typeof(EmployeeConverter))]:
=== With Converter ===
Code: 000
Name: Test
Surname: Testing
Workplace: At office
如果我从我获得的 Employee 类中删除[JsonConverter(typeof(EmployeeConverter))]:
=== With Converter ===
Code:
Name:
Surname:
Workplace: At Home!!
我的目标是获得:
=== With Converter ===
Code: 000
Name: Test
Surname: Testing
Workplace: At Home!!
转换器是否缺少某些东西?
【问题讨论】:
-
“转换器是否遗漏了什么?” - 我们怎么知道?你还没有发布它的代码。
-
它在链接中,但我会编辑答案.. 谢谢
标签: c# json.net json-deserialization