[英]C# Check for !null and string.Empty on a JSON response throws FormatException
我在期望JSON响应的方法中编写了一个简单的API调用...没什么特别的:
// [API call...]
dynamic responseString = JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result);
item.category = responseString.category;
item.shortDescription = responseString.shortDescription;
item.countryOfManufacture = responseString.manufacturerCountry ?? "DE";
有时API并没有提供所有必需的参数...所以我尝试检查是否is null
和is string.Empty
并引发一个对话框,用户可以在其中输入缺少的值...
但是这个:
if (responseString.weight == null ||responseString.weight == string.Empty )
{
DialogArgs args = new DialogArgs();
args.Add("Gewicht");
OnMissingValue?.Invoke(args);
item.weight = args.Get<float>("Gewicht");
}
else
{
item.weight = Convert.ToSingle(responseString.weight) / 1000;
}
要么
if (string.IsNullOrEmpty(responseString.weight))
抛出FormatException 。 如果我检查是否is null
或is string.Empty
它就像一个魅力。 我知道ref和值类型之间的差异,并认为可能存在问题...但是,我想知道为什么它的行为如此...
预先感谢...对不起,我的英语...
马库斯
好的,我明白了... dynamic
描述符是原因。 您必须将其转换为这样的字符串 :
if (string.IsNullOrEmpty((string)responseString.weight))
...谢谢你的努力
马库斯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.