简体   繁体   中英

Nested Object Deserialization of JSON results in an empty object

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[""] )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM