Deserializing JSON with C # JavaScriptSerializer

I am experimenting with JavaScriptSerializer to deserialize some JSON in C # and ask a couple of questions regarding the use of DataMember.

  • I want my DataContract class to have a property called "Details" that displays a "ring" JSON object. If I set DataMember Name = "rings" and name the property "Rings", everything will work as expected. However, if I named the property "Parts" (leaving the "DataMember Name =" ring). Parts are always zero.

    // this is always null [DataMember(Name = "rings")] public ArrayList Parts { get; set; } // this works fine [DataMember(Name = "rings")] public ArrayList Rings { get; set; } 
  • With deserialization, you can map multiple json objects to a single property. For example, the input json string may not contain a β€œring”, but rather a β€œdot” or β€œline”. Can I map all three types to the Parts property?

+4
source share
2 answers

JavaScriptSerializer is located in System.Web.Extensions and does not know about DataMemberAttribute .

Try DataContractJsonSerializer , which is located in System.Runtime.Serialization.Json (.net 40 - System.Runtime.Serialization.dll, .net 3.5 - System. ServiceModel.Web.dll)

+4
source

I recommend you use some other JSON implementation for .NET. There are many open source ones that do not require class changes. You just need to pass your object, and they know what to do.

0
source

Source: https://habr.com/ru/post/1305112/


All Articles