JsonConvert.DeserializeObject<ExpandoObject>

using Newtonsoft.Json.Converters;
using System.Dynamic;

            dynamic responseObj = JsonConvert.DeserializeObject<ExpandoObject>(responseJson, new ExpandoObjectConverter());
            var fileId = int.Parse(responseObj.Data.FileId.ToString());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你使用 `JsonConvert.DeserializeObject<T>` 方法将 JSON 字符串反序列化为一个对象,但是对象的某些属性为空,有可能是以下原因导致: 1. JSON 字符串中该属性对应的值为 `null`。在这种情况下,反序列化后的对象的对应属性值也会是 `null`。 2. 对象的属性没有设置 `JsonProperty` 特性。如果你使用 `JsonProperty` 指定了 JSON 字符串中该属性的名称,但是在对象的属性上没有设置该特性,那么 `DeserializeObject<T>` 方法就无法将 JSON 字符串中的值赋值给对象的属性,导致属性值为空。 例如,假设有如下 JSON 字符串: ```json { "name": "Tom", "age": 20, "address": null } ``` 我们定义一个对应的 C# 类型 `Person`: ```csharp public class Person { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("age")] public int Age { get; set; } [JsonProperty("address")] public Address Address { get; set; } } public class Address { [JsonProperty("city")] public string City { get; set; } [JsonProperty("country")] public string Country { get; set; } } ``` 我们使用 `JsonConvert.DeserializeObject<T>` 方法将 JSON 字符串转换为 `Person` 对象: ```csharp string json = "{...}"; // 上面的 JSON 字符串 Person person = JsonConvert.DeserializeObject<Person>(json); ``` 此时,`person` 对象的 `Name` 属性值将为 "Tom",`Age` 属性值为 20,但是 `Address` 属性值为空,因为在 JSON 字符串中 `address` 对应的值为 `null`。如果你想要避免该问题,可以在定义对象的属性时设置默认值,例如: ```csharp public class Person { [JsonProperty("name")] public string Name { get; set; } = string.Empty; [JsonProperty("age")] public int Age { get; set; } [JsonProperty("address")] public Address Address { get; set; } = new Address(); } public class Address { [JsonProperty("city")] public string City { get; set; } = string.Empty; [JsonProperty("country")] public string Country { get; set; } = string.Empty; } ``` 这样,即使 JSON 字符串中对应的值为 `null`,反序列化后的对象的属性值也不会为空。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值