在C#中迭代JSON对象

70

我正在使用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条件:if (list.Any(e => e.id =="3718")) { //How do get the excat displayName which has passed the if condtion }请指导我该怎么做。 - user1539205
3个回答

120
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;
}

它提示缺少对Microsoft.CSharp和System.Core的引用。我已经添加了这两个引用。这是一个ASP.NET应用程序。 - require_once
4
很遗憾,“dynamic”关键字只能在4.0及以上版本的框架中使用 :( - SHEKHAR SHETE
太棒了!!第一种解决方案在.NET Core 2.1中运行得很好。 - Daniel Silva
@SHEKHARSHETE,您必须通过右键单击项目/Add/References../然后选择Microsoft.CSHARP来向您的项目添加Microsoft.CSHAP引用。 - Christophe Chenel

61
你可以使用JsonTextReader来读取JSON文件并遍历其中的token:
using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
    while (reader.Read())
    {
        Console.WriteLine("{0} - {1} - {2}", 
                          reader.TokenType, reader.ValueType, reader.Value);
    }
}

17
虽然这不是必需的,但这是唯一允许您在不事先知道结构的情况下迭代 JObject 的答案。 - david.barkhuizen
7
这是一个非常好的答案,它提供了获取解析后 JSON 的完全控制的选项。非常有用,谢谢! - Zoran

0

这对我有用,将嵌套的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";
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接