简体   繁体   中英

Deserializing JSON with JavaScriptSerializer C#

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

  1. I want my DataContract class to have a property called "Parts" that maps to a JSON object "rings". If I set the DataMember Name="rings" and name the property "Rings" everything works as expected. However, if I name the property "Parts" (leaving the DataMember Name="rings"). Parts is always null.

     // this is always null [DataMember(Name = "rings")] public ArrayList Parts { get; set; } // this works fine [DataMember(Name = "rings")] public ArrayList Rings { get; set; } 
  2. Upon deserialization, is it possible to map multiple json objects to a single property. For example, the input json string may not contain "rings", but rather "point" or "line". Can I map all three types to the Parts property?

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

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

I recommend that you use some other JSON implementation for .NET. There are many of them open source that don't require changing classes. You simply have to pass your object and they know what to do.

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