Need Help Stepping Through Deserialized Object

P

pbd22

I am having a hard time figuring out how to expose (& loop through)
the properties of my Categories class which was serialized (using
JSON) in a WCF service and deserialized on the server as illustrated
below.

JavaScriptSerializer serializer = new JavaScriptSerializer();
Category cat = serializer.Deserialize<Category>(param1);

// Missing a cast here?

foreach (var c in cat)
{
ele.InnerHtml += String.Format("<option value={0}>{1} &gt;</
option>",
c.field.id, c.field.path);
}

Where (I gather) I am going wrong is that I have to cast my Category
object as either ICollection or IEnumerable in order to access
GetEnumerator()? I think this is the step that I need advice on (if,
indeed, I am barking up the right tree?). I'd seriously appreciate
code examples in answers.

Thanks.
 
P

pbd22

Prior to serialization, "param1" is effectively "dtSerialized" which
looks like this:

Category myCategory = new Category();

foreach (DataRow row in dt.Rows)
{
myCategory.field.id = (int)row["categoryid"];
myCategory.field.path = (string)row["cat_path"];
}

dtSerialized = JSONHelper.Serialize<Category>(myCategory)

This is my Category Class:

public class Category {
public Category() { }
public Field field = new Field();
public string model{get; set;}
public int jsonkey { get; set; }
}

public class Field {
public Field(){ }
public int level { get; set; }
public int id { get; set; }
public int parentid { get; set; }
public string name { get; set; }
public string path { get; set; }
}
 
P

Peter Duniho

Prior to serialization, "param1" is effectively "dtSerialized" which
looks like this:

Category myCategory = new Category();

foreach (DataRow row in dt.Rows)
{
myCategory.field.id = (int)row["categoryid"];
myCategory.field.path = (string)row["cat_path"];
}

dtSerialized = JSONHelper.Serialize<Category>(myCategory)

Your Category class doesn't implement IEnumerable. There's no way to get
an IEnumerable from it.

Furthermore, your initialization code looks suspect to me (not even
counting the use of public fields, which is generally a bad idea), as you
simply create a single Field object, assign it to the "field" field, and
then copy new values into the Field object with each iteration of your
loop. All but the values for the last iteration are simply discarded.

If you want to get an IEnumerable from your object when deserializing, it
has to implement IEnumerable in the first place.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top