簡體   English   中英

C#檢查!null和string.JSON響應上的Empty引發FormatException

[英]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 nullis 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 nullis string.Empty它就像一個魅力。 我知道ref和值類型之間的差異,並認為可能存在問題...但是,我想知道為什么它的行為如此...

預先感謝...對不起,我的英語...

馬庫斯

好的,我明白了... dynamic描述符是原因。 您必須將其轉換為這樣的字符串

if (string.IsNullOrEmpty((string)responseString.weight))

...謝謝你的努力

馬庫斯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM