gpt4 book ai didi

c# - 使用 json.net 序列化值类型

转载 作者:行者123 更新时间:2023-11-30 17:52:46 28 4
gpt4 key购买 nike

我正在尝试进行 ajax 调用以从某个国家/地区获取状态,但我一直收到无效的强制转换异常。我将 MVC4 与 json.NET 一起使用。我可以在我的测试中毫无问题地序列化对象,但是当我进行 ajax 调用时,我不断收到错误。

这是值类型:

[JsonConverter(typeof(ValueObjectConverter))]
public class Code : IValueObject
{
private readonly string _code;

private Code(string code)
{
_code = code;
}

public override string ToString()
{
return _code;
}

public static implicit operator Code(string code)
{
return new Code(code);
}

public static implicit operator String(Code code)
{
return code.ToString();
}
}

这是我的对象:

public class CountryState : Entity
{
public Code CodeWPS { get; set; }
public Code CodeIAM { get; set; }
public Name Description { get; set; }
}

这是 jsonconverter:

public class ValueObjectConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(IValueObject));
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return (IValueObject)existingValue;
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var item = (IValueObject)value;
writer.WriteValue(item.ToString());
writer.Flush();
}
}

这是 API 方法:

    public IEnumerable<CountryState> GetStatesByCountry(string codeType, string countryCodeIam)
{
var states = _getAllCountriesQueryHandler.Handle(countryCodeIam);
return states;
}

这是我用 Firebug 得到的错误:

    {"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type    failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Error getting value from 'CodeWPS' on 'CNH.CSCN.BBS.Entities.CountryState'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":"   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClassd.<WriteToStreamAsync>b__c()\r\n   at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Unable to cast object of type 'System.String' to type 'CNH.CSCN.BBS.Entities.ValueTypes.Code'.","ExceptionType":"System.InvalidCastException","StackTrace":"   at GetCodeWPS(Object )\r\n   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"}}}

更新:

我添加了一个合约解析器:

public class SpecialContractResolver : DefaultContractResolver
{
protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
{
if (member.MemberType == MemberTypes.Property)
{
var pi = (PropertyInfo)member;
if (typeof(IValueObject).IsAssignableFrom(pi.PropertyType))
{
return new IValueObjectValueProvider(member, pi.PropertyType);
}
}
else if (member.MemberType == MemberTypes.Field)
{
var fi = (FieldInfo)member;
if (typeof(IValueObject).IsAssignableFrom(fi.FieldType))
{
return new IValueObjectValueProvider(member, fi.FieldType);
}
}

return base.CreateMemberValueProvider(member);
}
}

和一个 IValueProvider:

public class IValueObjectValueProvider : IValueProvider
{
private readonly object _defaultValue;
private readonly IValueProvider _underlyingValueProvider;


public IValueObjectValueProvider(MemberInfo memberInfo, Type underlyingType)
{
_underlyingValueProvider = new DynamicValueProvider(memberInfo);
_defaultValue = underlyingType;
}

public void SetValue(object target, object value)
{
target = value;
}

public object GetValue(object target)
{
return target.ToString();
}
}

我知道我在正确的轨道上,我不再收到错误消息,但结果是:

对象 { CodeWPS="CNH.CSCN.BBS.Entities.CountryState", CodeIAM="CNH.CSCN.BBS.Entities.CountryState", Description="CNH.CSCN.BBS.Entities.CountryState"}

我认为我的 contractresolver 和 ivalueprovider 还不是 100% 正确...

最佳答案

是因为这段代码:

public override bool CanConvert(Type objectType)
{
return (objectType == typeof(IValueObject));
}

您的 objectType 不是 IValueObject,它是 Code - 所以 CanConvert 返回 false 并且您的转换器未被使用。您的代码应如下所示:

return typeof(IValueObject).IsAssignableFrom(objectType);

在这个条件下,实现类也匹配。

关于c# - 使用 json.net 序列化值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18145251/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com