C#类型转换错误求助:Int64转String失败及无法转为Integer
解决方案:C#类型转换错误处理
问题根源
你的代码中,Json反序列化Dictionary<string, object>时,数字类型的OBJECTID会被解析为Int64(long)而非string,直接用(string)强制转换会触发Unable to cast object of type system int64 to type system string错误;如果OBJECTID是其他非数字类型,int.Parse会触发Unable to convert object to integer错误。
可行解决方案
方案1:直接转换(简单场景)
如果确定OBJECTID的数值在int范围内,可直接用Convert.ToInt32处理,它支持从long、string等多种类型转换:
gJFeature.id = Convert.ToInt32(featureProperties["OBJECTID"]);
或者显式转换为long再转int:
gJFeature.id = (int)(long)featureProperties["OBJECTID"];
方案2:类型判断+安全转换(通用场景)
覆盖多种可能的类型,避免异常:
object objId = featureProperties["OBJECTID"]; if (objId is long longId) { gJFeature.id = (int)longId; } else if (objId is string strId && int.TryParse(strId, out int intId)) { gJFeature.id = intId; } else if (objId is int intIdDirect) { gJFeature.id = intIdDirect; } else { // 根据业务需求处理,比如抛出异常或设置默认值 throw new InvalidCastException("OBJECTID无法转换为int类型"); }
方案3:使用JObject替代Dictionary(推荐)
利用Json.NET的JObject来处理Json,它的类型转换更灵活:
JObject featureProperties = JObject.Parse(properties); gJFeature.id = featureProperties["OBJECTID"].Value<int>();
如果OBJECTID可能为空,可改用可空类型再处理:
int? id = featureProperties["OBJECTID"]?.Value<int?>(); if (id.HasValue) { gJFeature.id = id.Value; } else { // 处理空值情况 }
内容的提问来源于stack exchange,提问作者Parthasarathi U
相关产品推荐
相关产品推荐

