【问题标题】:Iterating over JSON object in C#在 C# 中迭代​​ JSON 对象
【发布时间】:2025-11-21 00:40:02
【问题描述】:

我在 C# 中使用 JSON.NET 来解析来自 Klout API 的响应。我的回复是这样的:

[
  {
    "id": "5241585099662481339",
    "displayName": "Music",
    "name": "music",
    "slug": "music",
    "imageUrl": "http://kcdn3.klout.com/static/images/music-1333561300502.png"
  },
  {
    "id": "6953585193220490118",
    "displayName": "Celebrities",
    "name": "celebrities",
    "slug": "celebrities",
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/celebrities_b32741b6703151cc7bd85fba24c44c52.png"
  },
  {
    "id": "5757029936226020304",
    "displayName": "Entertainment",
    "name": "entertainment",
    "slug": "entertainment",
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/Entertainment_7002e5d2316e85a2ff004fafa017ff44.png"
  },
  {
    "id": "3718",
    "displayName": "Saturday Night Live",
    "name": "saturday night live",
    "slug": "saturday-night-live",
    "imageUrl": "http://kcdn3.klout.com/static/images/icons/generic-topic.png"
  },
  {
    "id": "8113008320053776960",
    "displayName": "Hollywood",
    "name": "hollywood",
    "slug": "hollywood",
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/hollywood_9eccd1f7f83f067cb9aa2b491cd461f3.png"
  }
]

如您所见,它包含 5 个id 标签。也许下次它会是 6 或 1 或其他数字。我想遍历 JSON 并获取每个 id 标签的值。在不知道会有多少的情况下,我无法运行循环。我该如何解决这个问题?

【问题讨论】:

  • 您好,先生,我的情况与您的情况相似,请建议,我该怎么做。我想设置一个条件,根据列表中的 id 获取显示名称。如果我有 IF 条件,例如 ex:if (list.Any(e => e.id =="3718")) { //How do get the excat displayName which has passed the if condtion } 请在此处指导我

标签: c# json c#-4.0 json.net


【解决方案1】:
dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
    Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName, 
        item.slug, item.imageUrl);
}

var list = JsonConvert.DeserializeObject<List<MyItem>>(json);

public class MyItem
{
    public string id;
    public string displayName;
    public string name;
    public string slug;
    public string imageUrl;
}

【讨论】:

  • 它说缺少对 Micrsofot.CSHARp 和 System.Core 的引用。我添加了对两者的引用。它是 APS.NET 应用程序
  • 不幸的是 'dynamic' 关键字从框架 4.0 开始可用:(
  • 太棒了!第一个解决方案就像 .NET Core 2.1 中的魅力
  • @SHEKHARSHETE 您必须通过在您的项目/Add/References../ 上单击右键将引用 Microsoft.CSHAP 添加到您的项目中,然后选择 Microsoft.CSHARP
【解决方案2】:

您可以使用JsonTextReader 读取 JSON 并遍历令牌:

using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
    while (reader.Read())
    {
        Console.WriteLine("{0} - {1} - {2}", 
                          reader.TokenType, reader.ValueType, reader.Value);
    }
}

【讨论】:

  • 虽然不是必需的,但这是唯一允许您在事先不知道结构的情况下遍历 JObject 的答案
  • 这是一个非常好的答案,它提供了完全控制已解析 JSON 的选项。很有用,谢谢!
【解决方案3】:

这对我有用,将嵌套的 JSON 转换为易于阅读的 YAML

    string JSONDeserialized {get; set;}
    public int indentLevel;

    private bool JSONDictionarytoYAML(Dictionary<string, object> dict)
    {
        bool bSuccess = false;
        indentLevel++;

        foreach (string strKey in dict.Keys)
        {
            string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
            JSONDeserialized+="\r\n" + strOutput;

            object o = dict[strKey];
            if (o is Dictionary<string, object>)
            {
                JSONDictionarytoYAML((Dictionary<string, object>)o);
            }
            else if (o is ArrayList)
            {
                foreach (object oChild in ((ArrayList)o))
                {
                    if (oChild is string)
                    {
                        strOutput = ((string)oChild);
                        JSONDeserialized += strOutput + ",";
                    }
                    else if (oChild is Dictionary<string, object>)
                    {
                        JSONDictionarytoYAML((Dictionary<string, object>)oChild);
                        JSONDeserialized += "\r\n";  
                    }
                }
            }
            else
            {
                strOutput = o.ToString();
                JSONDeserialized += strOutput;
            }
        }

        indentLevel--;

        return bSuccess;

    }

用法

        Dictionary<string, object> JSONDic = new Dictionary<string, object>();
        JavaScriptSerializer js = new JavaScriptSerializer();

          try {

            JSONDic = js.Deserialize<Dictionary<string, object>>(inString);
            JSONDeserialized = "";

            indentLevel = 0;
            DisplayDictionary(JSONDic); 

            return JSONDeserialized;

        }
        catch (Exception)
        {
            return "Could not parse input JSON string";
        }

【讨论】: