开发者

Deserializing JSON with JavaScriptSerializer C#

开发者 https://www.devze.com 2022-12-23 23:20 出处:网络
I am experimenting with JavaScriptSerializer to deserialize some JSON in C#, and have a couple of questions regarding the use of DataMember.

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 sin开发者_JAVA百科gle 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消