栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

C#Newtonsoft.Json.Linq.JValue始终返回Int64

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#Newtonsoft.Json.Linq.JValue始终返回Int64

释义:

  • 作者有意选择将所有int都返回,
    Int64
    以避免溢出错误,并且检查起来更容易(对于Json.NET内部而言,不是您自己)
  • 您可以使用自定义转换器(如链接答案中发布的转换器)来解决此问题。

这是一个真正的通用转换器;不能完全确定

CanConvert
支票,但对我有用的重要部分是允许
typeof(object)

/// <summary>/// To address issues with automatic Int64 deserialization -- see https://stackoverflow.com/a/9444519/1037948/// </summary>public class JsonInt32Converter : JsonConverter{    #region Overrides of JsonConverter    /// <summary>    /// only want to deserialize    /// </summary>    public override bool CanWrite { get { return false; } }    /// <summary>    /// Placeholder for inheritance -- not called because <see cref="CanWrite"/> returns false    /// </summary>    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)    {        // since CanWrite returns false, we don't need to implement this        throw new NotImplementedException();    }    /// <summary>    /// Reads the JSON representation of the object.    /// </summary>    /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param><param name="objectType">Type of the object.</param><param name="existingValue">The existing value of object being read.</param><param name="serializer">The calling serializer.</param>    /// <returns>    /// The object value.    /// </returns>    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)    {        return (reader.TokenType == JsonToken.Integer) ? Convert.ToInt32(reader.Value)     // convert to Int32 instead of Int64 : serializer.Deserialize(reader);   // default to regular deserialization    }    /// <summary>    /// Determines whether this instance can convert the specified object type.    /// </summary>    /// <param name="objectType">Type of the object.</param>    /// <returns>    /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.    /// </returns>    public override bool CanConvert(Type objectType)    {        return objectType == typeof(Int32) ||     objectType == typeof(Int64) ||     // need this last one in case we "weren't given" the type     // and this will be accounted for by `ReadJson` checking tokentype     objectType == typeof(object) ;    }    #endregion}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449282.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号