【问题标题】:Can't assign item value to property list in c# [closed]无法在c#中将项目值分配给属性列表[关闭]
【发布时间】:2021-11-07 04:13:15
【问题描述】:

我有我的模型类,像这样:

        public class Info
        {
            public string status { get; set; }
        }

        public class MyItem
        {
            public MyItem()
            {
                info = new List<Info>();
            }
            public List<Info> info { get; set; }
            public string name { get; set; }
            public string address { get; set; }
            public int? age { get; set; }
        }

        public class Root
        {
            public List<MyItem> data { get; set; }
        }

我正在使用 RestSharp 获取 json 文件,然后将其反序列化为我的模型。然后我想在我的信息列表属性中分配新项目。但我在info 列表中没有任何值:

{
"data": [
{
   "info": [],
   "name": "John Doe",
   "address": "2541 Cheshire Road",
   "age": null
},
.
.
.

到目前为止,这是我的代码:

            var client = new RestClient("XXX");
            client.UseNewtonsoftJson();
            var request = new RestRequest("XXX");
            var response = client.Execute(request);

            var result = JsonConvert.DeserializeObject<Root>(response.Content);
            var foo = new MyItem();
            foreach (var item in result.data)
            {
                var total = 0;
                total = item.GetType()
                    .GetProperties()
                    .Select(x => x.GetValue(item, null))
                    .Count(v => v is null || (v is string a && 
                     string.IsNullOrWhiteSpace(a)));

                foo.info.Add(new Info() { status = "test" }); // add to list here

            }
            return Ok(result);

我不知道我是否犯了错误,但我认为到目前为止我是对的。我读过一些类似的问题,但我仍然无法弄清楚如何解决这个问题。

【问题讨论】:

  • @zaggler 是的,这就是我添加 foo.info.Add(new Info() { status = "test" }); 的原因,但我最终得到了空列表 []
  • @zaggler item.info.Add(new Info() { status = "test" }); 工作正常
  • @zaggler 我将新项目添加到新对象,然后返回反序列化的项目,如果这是我的错误,我想知道,但是这花了我很多时间
  • 仅供参考,如果您只是要在下一行重新分配 0total,则毫无意义。

标签: c# json .net-core


【解决方案1】:

您将元素添加到MyItem 的新实例,而不是result 中的任何实例。完全摆脱 foo 并将其添加到 result 中的元素中:

var result = JsonConvert.DeserializeObject<Root>(response.Content);
foreach (var item in result.data)
{
    var total = 0;
    total = item.GetType()
        .GetProperties()
        .Select(x => x.GetValue(item, null))
        .Count(v => v is null || (v is string a && 
         string.IsNullOrWhiteSpace(a)));

    // Add to "item", not to "foo"
    item.info.Add(new Info() { status = "test" });

}
return Ok(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多