C# automatic property deserialization of JSON

前端 未结 4 690
予麋鹿
予麋鹿 2020-11-28 10:56

I need to deserialize some JavaScript object represented in JSON to an appropriate C# class. Given the nice features of automatic properties, I would prefer having them in t

相关标签:
4条回答
  • 2020-11-28 11:24

    I'm assuming you are passing data via a web service. If you are using the WebService class with the ScriptMethod attribute uncommented-out, the web service methods can read JSON natively. They even use the same JavaScriptSerializer that was mentioned above. If you are using WCF I'm a little more fuzzy on the logic.

    But make sure your JSON object are returning data for EVERY property in your class. In your error, there is mention of a Breed property that is not in your example.

    Also, on the JavaScript side, do to the dynamic nature of JavaScript it is easy to add new properties to your objects. This can sometimes lead to circular references. You should remove any extra data that you might have added (just as you are sending data via the web method, then add it again once you are done).

    0 讨论(0)
  • 2020-11-28 11:37

    What's happening here is the deserializer is trying to guess the name of your backing fields. You can solve this by adding explicit mappings (DataContract/DataMember attributes) like this:

    [DataContract]
    public class Cat
    {
        [DataMember]
        public string Name { get; set; }
    
        [DataMember]
        public string Breed { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-28 11:45

    You can do this with JavaScriptSerializer found in the System.Web.Script.Serialization namespace:

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Cat c = serializer.Deserialize<Cat>(jsonString);
    

    I have POCO objects with automatic properties and this works just fine.

    EDIT: I wrote about JSON Serializers in .NET which compares this serializer with DataContractJsonSerializer.

    0 讨论(0)
  • 2020-11-28 11:46

    baretta's answer solved the k__BackingField bloat for me. Just a tiny addendum that you can decorate this class to auto serialize into either XML or JSON in a similar way:

    [Serializable, XmlRoot, DataContract]
    public class Cat
    {
      [XmlElement]
      [DataMember]
      public string Name { get; set; }
      [XmlElement]
      [DataMember]
      public string Breed { get; set; }
    }
    

    ... and then use a DataContractJsonSerializer or XmlSerializer to prepare it for your endpoint.

    0 讨论(0)
提交回复
热议问题