user163757
user163757

Reputation: 7025

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?

Upvotes: 4

Views: 2145

Answers (2)

Sky Sanders
Sky Sanders

Reputation: 37104

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)

Upvotes: 4

thelost
thelost

Reputation: 6694

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.

Upvotes: 0

Related Questions