如果无法向
[JsonConstructor]目标类添加属性(因为您不拥有代码),则通常的解决方法是
JsonConverter按照@James
Thorpe在注释中的建议创建自定义。这很简单。您可以将JSON加载到中
JObject,然后从中选择各个属性以实例化
Claim实例。这是您需要的代码:
class ClaimConverter : JsonConverter{ public override bool CanConvert(Type objectType) { return (objectType == typeof(System.Security.Claims.Claim)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jo = JObject.Load(reader); string type = (string)jo["Type"]; string value = (string)jo["Value"]; string valueType = (string)jo["ValueType"]; string issuer = (string)jo["Issuer"]; string originalIssuer = (string)jo["OriginalIssuer"]; return new Claim(type, value, valueType, issuer, originalIssuer); } public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); }}要使用转换器,只需将其实例传递给
JsonConvert.DeserializeObject<T>()方法调用:
Claim claim = JsonConvert.DeserializeObject<Claim>(json, new ClaimConverter());
小提琴:https :
//dotnetfiddle.net/7LjgGR



