简体   繁体   English

使用JavaScriptSerializer C#反序列化JSON

[英]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. 我正在尝试使用JavaScriptSerializer来反序列化C#中的一些JSON,并且有一些关于DataMember使用的问题。

  1. I want my DataContract class to have a property called "Parts" that maps to a JSON object "rings". 我希望我的DataContract类具有一个名为“Parts”的属性,该属性映射到JSON对象“ring”。 If I set the DataMember Name="rings" and name the property "Rings" everything works as expected. 如果我设置DataMember Name =“rings”并将属性命名为“Rings”,则一切都按预期工作。 However, if I name the property "Parts" (leaving the DataMember Name="rings"). 但是,如果我将属性命名为“Parts”(保留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. 反序列化后,是否可以将多个json对象映射到单个属性。 For example, the input json string may not contain "rings", but rather "point" or "line". 例如,输入json字符串可能不包含“环”,而是“点”或“行”。 Can I map all three types to the Parts property? 我可以将所有三种类型映射到Parts属性吗?

JavaScriptSerializer is in System.Web.Extensions and does not know about DataMemberAttribute . JavaScriptSerializer位于System.Web.Extensions ,不了解DataMemberAttribute

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

I recommend that you use some other JSON implementation for .NET. 我建议你使用.NET的其他一些JSON实现。 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. 你只需要传递你的对象,他们就知道该怎么做了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM