【问题标题】:How to use ".Where" condition with Json object in c#?如何在 C# 中将“.Where”条件与 Json 对象一起使用?
【发布时间】:2020-02-22 13:59:05
【问题描述】:

我正在开发一个 Xamarin 项目(使用 Newtonsoft.Json)。尝试反序列化一个 json 并使用它(json 的全部和部分)。

我有一个 json 列表。我可以列出所有列表,但无法从列表中选择,例如;其中“年龄 > 40”。

我的 json;

{"data":
    [
    {
    "contact_id":"1",
    "contact_date":"2020-02-19",
    "contact_stat":"new"
    }
    ,
    {
    "contact_id":"2",
    "contact_date":"2020-02-19",
    "contact_stat":"old"
    }
    ,
    {
    "contact_id":"3",
    "contact_date":"2020-02-19",
    "contact_stat":"new"
    }
    ]
}

我的班级;

public class AllSource
{
    public string contact_id{ get; set; }
    public DateTime contact_date{ get; set; }
    public string contact_stat{ get; set; }
}
public class AllList
{
    public List<AllSource> data { get; set; }
}

我在我的 .cs 中尝试过这个 => 这样我就可以使用所有这些了;

var response = await client.GetAsync("http://example.com/json2.asp");
string itemJson = response.Content.ReadAsStringAsync().Result;
AllList ObjJson = new AllList();
   if (itemJson != "")
       {
          ObjJson = JsonConvert.DeserializeObject<AllList>(itemJson);
          mydata = ObjJson.data;
       }

我正在尝试这样的事情(只想获得“stat=new”);

ObjJson.Where(x => x.stat == "new");

但我收到此错误;

AllList 不包含“Where”的定义,并且找不到接受第一个类型参数的可访问扩展方法“Where”。

尝试了很多建议,但无法管理。希望我清楚地解释了我的问题。

【问题讨论】:

  • ObjJson.data.Where(x =&gt; x.contact_stat == "new"); 你需要过滤data 这是AllSource的列表。
  • 您正在尝试过滤 AllList 类,但您无法过滤,这就是错误的原因。
  • 天啊。我是个白痴。我怎么看不到。我要睡觉。非常感谢。

标签: c# json serialization json.net where-clause


【解决方案1】:

试试这个:

var filteredData = ObjJson.data.Where(x => x.contact_stat == "new");

【讨论】:

  • 非常感谢。我的错就是两天不睡觉。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 2018-04-16
  • 2016-11-15
  • 2012-05-21
  • 2014-08-21
  • 2012-03-05
  • 1970-01-01
相关资源
最近更新 更多