NewtonSoft JArray - how to select multiple elements with LINQ

久未见 提交于 2020-08-08 07:21:57

问题


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.

enter image description here

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!