Loop trought Dictionary only for a key in

2019-09-09 23:11发布

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}

using the code:

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

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

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

but i got error:

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

Solved replacing the dictionary with a class, thank you

5条回答
Animai°情兽
2楼-- · 2019-09-09 23:36

A possible solution:

static void Main(string[] args) {

    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 labels = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
    IEnumerable inner_labels = labels["labels"] as IEnumerable;
    if (inner_labels != null) {
        foreach (var outer in inner_labels) { 
            Console.WriteLine(outer);
        }
    }

}

Otherwise, you can create a class with deserialization information and instruct the deserializer to deserialize your json string to that type:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Xml.Serialization;

[Serializable]
public class JsonData {

    [XmlElement("labels")]
    public List<JsonLabel> labels { get; set; }

    [XmlElement("0")]
    public int zero { get; set; }

    [XmlElement("error")]
    public bool error { get; set; }

    [XmlElement("status")]
    public int status { get; set; }


}

[Serializable]
public class JsonLabel {
    [XmlElement("id")]
    public int id { get; set; }

    [XmlElement("descrizione")]
    public string descrizione { get; set; }

    [XmlElement("tipo")]
    public int tipo { get; set; }

    [XmlElement("template_file")]
    public string template_file { get; set; }

}

class Program {


    static void Main(string[] args) {
        string json = @"your json string here...";
        var jsonData = new JavaScriptSerializer().Deserialize<JsonData>(json);
        foreach (var label in jsonData.labels) {
            Console.WriteLine(label.id);
        }
    }

}
查看更多
疯言疯语
3楼-- · 2019-09-09 23:43

Your problem is that you've defined the Type of Value for each dictionary entry as object. C# can't know how to loop over on object. So you need to work out what type is actually inside the object once the JavaScriptSerializer have parsed the JSON. One way is

var t = typeof(labels["labels"]);

Once you know what type the serializer is creating, all you need to do is cast the object back to that type. For example, assuming it's a list of objects

var labels = (List<object>)labels["labels"];
foreach (var label in labels)
{
}

Alternatively, if each object in the JSON is the same, you could try create the dictionary as the type you need. So you serializing becomes

var labels = new JavaScriptSerializer()
                 .Deserialize<Dictionary<string, List<object>>>(json); 
查看更多
Deceive 欺骗
4楼-- · 2019-09-09 23:57

You need to loop through your dictionary.

    foreach(KeyValuePair<string, Object> entry in labels)
     {
          // do something with entry.Value or entry.Key
     }

Once you start looping through it you will get access to key and value. Since you are interested to look at entry.value you can do operation on that easily. Currently your dictionary value is type of object which does not have an enumerator

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-09-10 00:00

Create a class to deserialize your json:

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

Edit / Paste special / Paste JSON as class

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; }
    }
查看更多
Emotional °昔
6楼-- · 2019-09-10 00:03

Could you please try below snippet? It might be help you.

foreach (var item in labels["labels"] as ArrayList)
        {
            Console.Write(item);
        }
查看更多
登录 后发表回答