0

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

marco burrometo
  • 1,055
  • 3
  • 16
  • 33
  • 1
    Your labels object looks more like an array. Try creating a class with those properties (id, decrizione, etc.) and deserialize your object to `Dictionary>`. – Andrei V Jan 22 '15 at 07:55
  • try this [link][1] this will help you [1]: http://stackoverflow.com/questions/348964/how-to-use-foreach-keyword-on-custom-objects-in-c-sharp – vijay.k Jan 22 '15 at 08:05

5 Answers5

3

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; }
    }
Eric Bole-Feysot
  • 13,949
  • 7
  • 47
  • 53
0

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

qamar
  • 1,437
  • 1
  • 9
  • 12
0

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

}
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
0

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); 
Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
0

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

foreach (var item in labels["labels"] as ArrayList)
        {
            Console.Write(item);
        }
Ashish Sapkale
  • 540
  • 2
  • 13