简体   繁体   中英

JSON Deserialization Despair (unable to deserialize nested types)

There are probably 500 questions like this on SO, and a million websites out there all offering tidbits of information - but I just can't see the wood for the trees. This seems like it should be embarrassingly simple to do, but I just can't make it work.

I have a WCF webservice that returns a serialized JSON object:

[OperationContract(Name = "PeopleData"), WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "people/{subset}", ResponseFormat = WebMessageFormat.Json)]
PeopleObject GetPeople(string subset);

This works - if I hit that URI from a browser, GetPeople is invoked and returns a JSON-serialized PeopleObject (actual data values redacted for privacy here):

{"HashValue":"XXXXX","People":[{"EmailAddress":"XXXXX","EmployeeID":99999,"Gender":"X","JobTitle":"XXXXX","Office":"","PreferredName":"XXXXX","Surname":"XXXXX","WorkExtensionNumber":"XXXXX","WorkPhoneNumber":"XXXXX","Department":"XXXXX","DeskNumber":"XXXXX","EmploymentClassification":"XXXXX","InternationalExtensionNumber":"XXXXX","IsFirstAider":false,"Languages":[{"LanguageID":9,"LanguageSkillID":9},{"LanguageID":9,"LanguageSkillID":9}],"QualificationInitials":"XXXXX","QualificationTitle":"XXXXX","Secretaries":null,"WorkMobilePhoneNumber":"XXXXX"}],"RecordCount":"1","SizeBytes":"12345"}

In this example the PeopleObject payload contains just one Person object in the collection, but could contain many (depending on the parameter supplied in /{subset} .

Here is the class hierarchy for PeopleObject - it's a top-level container holding some metadata about the payload, and a List<> of Person objects. Those objects in turn have a bunch of simple type attributes, plus two further nested List<> of Language and Secretary objects (which may or may not be populated):

  [DataContract]
  public class PeopleObject
  {
    [DataMember]
    public string HashValue { get; set; }
    [DataMember]
    public List<Person> People { get; set; }
    [DataMember]
    public string RecordCount { get; set; }
    [DataMember]
    public string SizeBytes { get; set; }
  }

  [DataContract]
  public class Person
  {
    [DataMember]
    public string EmailAddress { get; set; }
    // <-- snip - lots of fields like this, no point listing them all here
    [DataMember]
    public bool IsFirstAider { get; set; }
    [DataMember]
    public List<Language> Languages { get; set; }
    [DataMember]
    public List<Secretary> Secretaries { get; set; }
  }

  [DataContract]
  public class Language
  {
    [DataMember]
    public int LanguageID { get; set; }
    [DataMember]
    public int LanguageSkillID { get; set; }
  }

  [DataContract]
  public class Secretary
  {
    [DataMember]
    public int EmployeeID { get; set; }
    [DataMember]
    public char FirstSurnameLetter { get; set; }
  }

So far, so good - WCF responds with a JSON structure that contains all the fields and their contents. Now to deserialize that structure in a client application (using the same class hierarchy definitions):

  // I have a little helper-class to manage the WCF request and return a Stream
  using (Stream response = wcfHelper.GetRequestResponseStream(MY_WCF_URI))
  {
    // This is debug code to prove the response arrives as expected - it does
    //StreamReader sr = new StreamReader(response);
    //Console.WriteLine("\nResponse:\n{0}", sr.ReadToEnd());

    // Deserialise the response
    DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(PeopleObject));
    PeopleObject p = (PeopleObject)dc.ReadObject(response);

    // The object shows 1 record (in the example) but nothing in the List<>
    Console.WriteLine("\nDeserialized records: '{0}' [{1}]", p.RecordCount, p.People.Count);
  }

So this correctly deserializes the container object, giving me the record count, hash value, and payload size in bytes. The object does also have a List<> of Person objects, but it's null - the content from the JSON response hasn't successfully rehydrated the List<> by creating and adding a Person object.

What am I missing? My understanding was that this rehydration of the C# object hierarchy from the JSON structure should happen automatically, so either that's not the case (and I need to write some code to make it happen) or it is, but I've missed something obvious.

I haven't done what you are doing before, but judging by the documentation , I'd assume the following would work:

List<Type> types = new List<Type>();
types.Add(typeof(Person));
types.Add(typeof(Language));
types.Add(typeof(Secretary));

DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(PeopleObject), types);
PeopleObject p = (PeopleObject)dc.ReadObject(response);

You basically need to tell the Serializer all the types it may encounter while serializing/deserializing your object.

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