问题
I have some JSON which I then parse to JArray object. I want to filter the JArray so it then has only two properties, Title and BodyText. But whatever I try I can only select one value using LINQ.
[HttpGet]
public JsonResult AjaxGetNewsItems()
{
string json = JsonConvert.SerializeObject(news.GetNewsItems(), formatting:Formatting.Indented);
var v = JArray.Parse(json);
//var items =
// v.Where(
// x =>
// x["Title"].ToString() != string.Empty &&
// x["BodyText"].ToString() != string.Empty)
// .Select(x => x["Title"])
// .ToList();
var title = (string) v[0]["Title"];
var titleBodytext = from p in v
select v[0]["Title"]["BodyText"];
foreach (var item in titleBodytext)
{
}
//var titleBodytext =
// from c in v[0]["Title"]["BodyText"]
// group c by c
// into g
// select new { };
//JArray a = JArray.FromObject(news.GetNewsItems());
//string titleBodytext = (string) newsItems["Title"]["Bodytext"];
return new JsonResult()
{
Data = json,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxJsonLength = Int32.MaxValue
};
}
I want to change this code:
var titleBodytext = from p in v
select v[0]["Title"]["BodyText"];
Title
and BodyText
are two keys values in my JArray.
See screenshot of JArray object. In element 0 there are key value elements.
回答1:
Try this way :
var titleBodytext = from p in v
select new
{
Title = (string)p["Title"],
Text = (string)p["BodyText"]
};
Or if you're sure v
always contain only one element :
var titleBodytext = new
{
Title = (string)v[0]["Title"],
Text = (string)v[0]["BodyText"]
};
BTW, your current code doesn't seems to do what you think. It has p in v
in the from
clause, but always select v[0]
regardless of current p
being the context. Anyway, this doesn't show wrong behavior in the case where v
only contain one element.
来源:https://stackoverflow.com/questions/26423398/newtonsoft-jarray-how-to-select-multiple-elements-with-linq