【问题标题】:jtoken string type conversionjtoken 字符串类型转换
【发布时间】:2021-07-20 18:25:19
【问题描述】:

我正在尝试将 JObject 字符串值保存为小数,然后插入 SQL 数据库。

insertWellData.Parameters.Add("@Latitude", SqlDbType.Decimal).Value = entityParams["Latitude"].ToObject<decimal>();

纬度值为空或字符串,即 49.4567 我在这上面有一个 if 语句来整理空值,所以我知道它们不是问题。

if (entityParams["Longitude"].Type == JTokenType.Null)

当我运行我的代码时,我立即得到错误

System.FormatException: 'Input string was not in a correct format.'

这是由于在代码运行开始时未定义纬度值引起的,还是我缺少其他东西?

【问题讨论】:

  • 那么是ToObject&lt;decimal&gt; 代码失败了吗?如果是这样,ADO.NET 部分就不那么相关了。如果您可以提供minimal reproducible example 以便我们自己测试,这将有所帮助。

标签: c# .net json.net


【解决方案1】:

这可能会有所帮助,您可以在将其与 TryParse 一起使用之前尝试将值解析为十进制。

TryParse,返回一个bool值表示转换是否成功,另外out部分给你转换的结果。因此,下一个代码将阻止使用无效结果:

    if (!Decimal.TryParse(entityParams["Latitude"].ToString(Formatting.None), out decimal Latitud))
    { 
    // if .TryParse fails - set the value for "Latitud" to 0.0
        Latitud = 0.0m;
    }

文档:https://docs.microsoft.com/en-us/dotnet/api/system.decimal.tryparse?view=net-5.0

【讨论】:

    猜你喜欢
    • 2012-08-09
    • 1970-01-01
    • 2020-04-30
    • 2014-12-08
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 2011-12-05
    相关资源
    最近更新 更多