gpt4 book ai didi

c# - DataContractJsonSerializer 设置值扩展点

转载 作者:行者123 更新时间:2023-11-30 15:48:27 27 4
gpt4 key购买 nike

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

namespace ConsoleApplication1 {
internal class Program {
private static void Main(string[] args) {
var pony = new Pony();
var serializer = new DataContractJsonSerializer(pony.GetType());
var example = @"{""Foo"":null}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(example.ToCharArray()));
stream.Position = 0;
pony = (Pony) serializer.ReadObject(stream);
// The previous line throws an exception.
}
}

[DataContract]
public class Pony {
[DataMember]
private int Foo { get; set; }
}
}

有时,序列化会在将 Int32 设置为 null 时引发强制转换错误。 有什么方法可以连接到 Json 序列化器吗?

最佳答案

恕我直言,最好的办法是更改 Foo Int32 输入至 System.Nullable<Int32> 因为这最能反射(reflect)它的语义(如果它可以为空)但是如果你不能修改这个类并且如果使用 DataContractJsonSerializer对您来说不是义务,Json.NET有允许您执行此操作的扩展点(它也恰好是 better performing )。

例如,您可以编写自定义类型转换器:

internal class NullableIntConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int);
}

public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
{
if (reader.Value == null)
{
return default(int);
}
return int.Parse(reader.Value.ToString());
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new System.NotImplementedException();
}
}

可以这样注册和使用:

internal class Program
{
private static void Main(string[] args)
{
var serializer = new JsonSerializer();
serializer.Converters.Add(new NullableIntConverter());
using (var reader = new StringReader(@"{""Foo"":null}"))
using (var jsonReader = new JsonTextReader(reader))
{
var pony = serializer.Deserialize<Pony>(jsonReader);
Console.WriteLine(pony.Foo);
}
}
}

关于c# - DataContractJsonSerializer 设置值扩展点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2599333/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com