且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScriptSerializer.Deserialize - 如何更改字段名称

更新时间:2023-01-16 08:18:56

我再次尝试使用 DataContractJsonSerializer 类.这解决了它:

I took another try at it, using the DataContractJsonSerializer class. This solves it:

代码如下:

using System.Runtime.Serialization;

[DataContract]
public class DataObject
{
    [DataMember(Name = "user_id")]
    public int UserId { get; set; }

    [DataMember(Name = "detail_level")]
    public string DetailLevel { get; set; }
}

测试是:

using System.Runtime.Serialization.Json;

[TestMethod]
public void DataObjectSimpleParseTest()
{
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataObject));

        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonData));
        DataObject dataObject = serializer.ReadObject(ms) as DataObject;

        Assert.IsNotNull(dataObject);
        Assert.AreEqual("low", dataObject.DetailLevel);
        Assert.AreEqual(1234, dataObject.UserId);
}

唯一的缺点是我必须将 DetailLevel 从枚举更改为字符串 - 如果您保留枚举类型,则 DataContractJsonSerializer 期望读取数值并失败.有关更多详细信息,请参阅 DataContractJsonSerializer 和 Enums.

The only drawback is that I had to change DetailLevel from an enum to a string - if you keep the enum type in place, the DataContractJsonSerializer expects to read a numeric value and fails. See DataContractJsonSerializer and Enums for further details.

在我看来这很糟糕,尤其是当 JavaScriptSerializer 正确处理它时.这是您尝试将字符串解析为枚举的例外情况:

In my opinion this is quite poor, especially as JavaScriptSerializer handles it correctly. This is the exception that you get trying to parse a string into an enum:

System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type DataObject. The value 'low' cannot be parsed as the type 'Int64'. --->
System.Xml.XmlException: The value 'low' cannot be parsed as the type 'Int64'. --->  
System.FormatException: Input string was not in a correct format

像这样标记枚举不会改变这种行为:

And marking up the enum like this does not change this behaviour:

[DataContract]
public enum DetailLevel
{
    [EnumMember(Value = "low")]
    Low,
   ...
 }

这似乎也适用于 Silverlight.

This also seems to work in Silverlight.