使用JavaScriptSerializer C#反序列化JSON

4

我正在尝试使用JavaScriptSerializer在C#中反序列化一些JSON,并且有一些关于使用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?

2个回答

4

JavaScriptSerializer位于System.Web.Extensions中,不支持DataMemberAttribute

尝试使用DataContractJsonSerializer,它位于System.Runtime.Serialization.Json中(.net 4.0-System.Runtime.Serialization.dll,.net 3.5-System.ServiceModel.Web.dll)


0

我建议您在.NET中使用其他JSON实现。有许多开源实现,不需要更改类。您只需要传递对象,它们就知道该怎么做。


有没有特别推荐的JSON库?看起来市面上有很多选择。 - user163757

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接