首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Web :无法序列化内容类型的响应体

Web :无法序列化内容类型的响应体
EN

Stack Overflow用户
提问于 2015-11-06 03:40:54
回答 1查看 4.1K关注 0票数 1

我正在使用ASP.NET MVC 5 Web。

我有许多api的现有应用程序,最近我实现了自定义JsonConverter,它将按时区转换日期。

代码语言:javascript
运行
复制
public class CustomInfoConverter : JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(CustomType);
    }
    public override bool CanRead
    {
        get
        {
            return false;
        }
    }
    public override bool CanWrite
    {
        get
        {
            return true;
        }
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var customType = (CustomType)value;
        if (customType == null || null== customType.TimeZone) return;
        //DateTime currentDateTime = customType.Date??DateTime.Now;
        DateTime currentDateTime = DateTime.SpecifyKind(customType.Date ?? DateTime.Now, DateTimeKind.Unspecified);

        DateTime userDateTime = TimeZoneInfo.ConvertTimeFromUtc(currentDateTime, customType.TimeZone);
        customType.Date = userDateTime;
        JsonSerializer innerSerializer = new JsonSerializer();
        foreach (var converter in serializer.Converters.Where(c => !(c is CustomInfoConverter)))
        {
            innerSerializer.Converters.Add(converter);
        }
        innerSerializer.Serialize(writer, customType);


    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }


}

在实现此自定义JsonConverter之后,除了一个api之外,所有api都在工作,该api正在异常下面抛出。

{“消息”:“发生了错误。”,“ExceptionMessage”:“‘ObjectContent`1 1’类型未能序列化内容类型‘application/ JSON的响应体;charset=utf-8’。”,ExceptionMessage "StackTrace":null,“InnerException”:{“消息”:“发生了错误。”,“ExceptionMessage”:“ExceptionMessage PropertyName in state属性将导致无效的JSON对象。”路径'Data.Forms'.","ExceptionType":"Newtonsoft.Json.JsonWriterException","StackTrace":“at Newtonsoft.Json.JsonWriter.AutoComplete(JsonToken tokenBeingWritten]\r\n at Newtonsoft.Json.JsonWriter.InternalWritePropertyName(String name)\r\n at Newtonsoft.Json.JsonTextWriter.WritePropertyName(String name,\r\n at Newtonsoft.Json.Serialization.JsonProperty.WritePropertyName(JsonWriter Newtonsoft.Json.JsonTextWriter.WritePropertyName(String)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter编写器,对象值,JsonObjectContract契约,\n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter编写器,对象值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\r\n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter编写器上,IEnumerable值,JsonArrayContract contract,JsonArrayContract成员,containerProperty存储,)\r\n在编写器,对象值,,成员,en26#,\r\n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter编写器,对象值,JsonObjectContract契约,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\r\n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter编写器,对象值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\r在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter编写器,对象值,Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter契约,成员,,\r\n在Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter的写入器,对象值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\r at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter,Object value,Type objectType)\r at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter,Object value,Type objectType)\r at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter,\r\n在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type类型下\r\n在System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type类型下\r\n在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type类型下\\r\n在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type类型下\\r\n在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type类型下,在对象值中,在流writeStream中,在HttpContent内容中)\r\n在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type类型,对象值,流writeStream,从抛出异常的前一个位置开始的堆栈跟踪的结束--在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task任务中--\r\n在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task任务中)\r\n在System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()"}}的System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n上

有关更多细节,您可以参考此链接

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-06 12:21:41

问题在于,在某些情况下,您是从WriteJson()返回的,没有写任何东西,特别是当customType.TimeZone == null

代码语言:javascript
运行
复制
    var customType = (CustomType)value;
    if (customType == null || null== customType.TimeZone) return;

这样做将导致无效的JSON对象,因为调用方已经写入了属性名称,因此:

{ "customType":}

尝试这样做会导致您正在看到的异常。

相反,您需要防止属性本身被序列化。但是,这在转换器中是不可能的,它需要在包含的类型中完成。

若要避免序列化具有空值的属性,应在NullValueHandling = NullValueHandling.Ignore中或在属性本身上设置串行化设置

代码语言:javascript
运行
复制
public class ContainerClass
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public CustomType CustomType { get; set; }
}

若要防止在属性TimeZone属性为null时序列化属性,应通过向包含的类型添加ShouldSerializeXXX()方法来使用条件属性序列化,其中XXX与属性名称完全匹配:

代码语言:javascript
运行
复制
public class ContainerClass
{
    public CustomType CustomType { get; set; }

    public bool ShouldSerializeCustomType()
    {
        return CustomType != null && CustomType.TimeZone != null;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33559080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档