Question

Good day

I am attempting to deserialize a JSON object to C# classes using a Javascriptserializer. This object contains a nested object. Here is a representation of the object:

[{"ObjA":"FOO",
  "SubObjA":{
    "A":0,
    "B":true,
    "C":2,
    "D":0.2
    },
  "ObjB":false,
  "ObjC":295,
  }]

In c#, I created the classes for these:

public class ClassA
{
    public string ObjA { get; set; }
    public Collection<SubObjA> SubObjA { get; set; }
    public bool ObjB { get; set; }
    public int ObjC { get; set; }


}

public class SubObjA
{
    public int A { get; set; }
    public bool B { get; set; }
    public int C { get; set; }
    public decimal D { get; set; }
}

When Deserializing the object, I see that the SubObjA Collection does not populate (Count = 0)

var Helper = new JavaScriptSerializer().Deserialize<ClassA[]>(Request["TheJSONIAmDeserializing"]);

Why is the collection not populating? (Tagged AJAX because of the Request[""] )

Was it helpful?

Solution

SubObjA in your example is a single object but in your class it is a collection, so JSON should look like

[{"ObjA":"FOO",
  "SubObjA":[{
    "A":0,
    "B":true,
    "C":2,
    "D":0.2
    }],
  "ObjB":false,
  "ObjC":295,
  }]

Note brackets around SubObjA.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top