简体   繁体   中英

Why does DataContractJsonSerializer skip deserializing some properties?

We ran into a weird problem recently where two properties from a JSON object weren't being deserialized.

Given this class:

[DataContract]
public class Hotel
{
  [DataMember]
  public string Name { get; set; }

  .... other properties

  [DataMember]
  public string double? Latitude { get; set; }

  [DataMember]
  public string double? Longitude { get; set; }

  .... other properties
}    

and a matching JSON string:

{
  "Address":"123 Maple Avenue",
  "Name":"My Awesome Hotel",
  "Phone":"+15550001212",
  "PostalCode":"",
  "Province":"ON",
  "latitude":45.421530,
  "longitude":-75.697193
}

Neither the latitude nor longitude properties were being set.

Here's the deserialization code:

public static object Deserialize(Type concreteType, string serialized)
{
   var jsonBytes = Encoding.UTF8.GetBytes(serialized);
   using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader
                           (jsonBytes, XmlDictionaryReaderQuotas.Max))
   {
      var dcjs = new DataContractJsonSerializer(concreteType);
      return dcjs.ReadObject(jsonReader);
   }
}

What was extremely puzzling is that other classes with the same latitutde / longitude properties were being deserialized correctly. To be clear: there were other classes deserializing JSON strings where the names in the JSON were lower-case and the C# properties were in PascalCase.

(Interestingly enough, JSON.Net was able to deserialize this without any problem)

So what was happening with DataContractJsonSerializer and this particular string?

As it turns out, DataContractJsonSerializer expects all the properties in the JSON string to be in alphabetical order if they're not capitalized. Changing the data to

{
  "Address":"123 Maple Avenue",
  "latitude":45.421530,
  "longitude":-75.697193
  "Name":"My Awesome Hotel",
  "Phone":"+15550001212",
  "PostalCode":"",
  "Province":"ON",
}

made the object deserialize perfectly.

(Leaving the properties in the same order and capitalizing the 'L' also worked, as expected)

纬度和经度在JSON中为小写字母,但对象的属性具有大写L

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