循环运行Dictionary& lt; string,object& gt;仅适用于C#中的键 [英] Loop trought Dictionary<string, object> only for a key in c#

查看:54
本文介绍了循环运行Dictionary& lt; string,object& gt;仅适用于C#中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串和对象字典,该字典是我反序列化此json答案所获得的:

I have a dictionary of strings and object that i obtained deserializing this json answer:

{"labels":[{"id":"1","descrizione":"Etichetta interna","tipo":"0","template_file":"et_int.txt"},{"id":"2","descrizione":"Etichetta esterna","tipo":"1","template_file":"et_ext.txt"}],"0":200,"error":false,"status":200}

使用代码:

var labels = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);   

现在,我只想循环遍历"labels"键内的对象.我尝试过

Now i want to loop only trought the objects inside the "labels" key. I tried

foreach (var outer in labels["labels"]){/* code */}

但是我得到了错误:

CS1579: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'.

解决了用类替换词典的问题,谢谢

推荐答案

创建一个类以反序列化json:

Create a class to deserialize your json:

要创建类,您可以将json复制到剪贴板中并使用

To create classes, you can copy the json in clipboard and use the

编辑/粘贴特殊内容/将JSON粘贴为类

在Visual Studio中(我使用vs2013).

in visual studio (I use vs2013).

    [TestMethod]
    public void test()
    {
        string json = "{\"labels\" : [{\"id\" : \"1\",\"descrizione\" : \"Etichetta interna\",\"tipo\" : \"0\",\"template_file\" : \"et_int.txt\"}, {\"id\" : \"2\",\"descrizione\" : \"Etichetta esterna\",\"tipo\" : \"1\",\"template_file\" : \"et_ext.txt\"}],\"0\" : 200,\"error\" : false,\"status\" : 200}";
        var root = JsonConvert.DeserializeObject<Rootobject>(json);

        foreach (var label in root.Labels)
        {
            //Use label.Id, label.Descrizione, label.Tipo, label.TemplateFile
        }
    }

    public class Rootobject
    {
        public Label[] Labels { get; set; }
        public int _0 { get; set; }
        public bool Error { get; set; }
        public int Status { get; set; }
    }

    public class Label
    {
        public string Id { get; set; }
        public string Descrizione { get; set; }
        public string Tipo { get; set; }
        public string TemplateFile { get; set; }
    }

这篇关于循环运行Dictionary&amp; lt; string,object&amp; gt;仅适用于C#中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆