简体   繁体   English

在C#中将JSON对象中的特定属性值转换为IEnumerable

[英]Convert specific attribute value in a JSON object to IEnumerable in C#

I have a JSON object that looks like this 我有一个看起来像这样的JSON对象

{
"totalCount": 2,
    "students": [{
        "name": "abc",
        "data": {
            "Maths": 20,
            "Science": 25
        },
        "score": 10.0
    },
    {
        "name": "xyz",
        "data": {
            "Maths": 44,
            "Science": 12
        },
        "score": 11.0
    }]
}

I want to deserialize this JSON object to an IEnumerable<String> that contains all the names. 我想将此JSON对象反序列化为包含所有名称的IEnumerable<String>

I want - private IEnumerable<String> GetAllNames(string json) to return ["abc","xyz"] 我想要- private IEnumerable<String> GetAllNames(string json)返回["abc","xyz"]

This is just sample data (and not homework!!). 这只是示例数据(而不是家庭作业!)。 Any advice on how to achieve this would be appreciated. 任何有关如何实现这一目标的建议将不胜感激。 I'm using Newtonsoft library but haven't been able to do this effectively yet. 我正在使用Newtonsoft库,但尚未能够有效地做到这一点。 I do not want to iterate through the objects and construct the list myself, any direct way of doing this? 我不想自己遍历对象并构造列表,这样做有任何直接方法吗?

EDIT - This is what I'm doing currently 编辑 -这是我目前正在做的

var studentList = new List<string>();

var json = JsonConvert.DeserializeObject<dynamic>(jsonString);

foreach (var data in json.students)
   {
     catalogsList.Add(data.name.toString());
   }

return catalogsList;

Try this: 尝试这个:

private IEnumerable<string> GetAllNames(string json)
{
    JObject jo = JObject.Parse(json);
    return jo["students"].Select(s => s["name"].ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM