温馨提示×

如何自定义C# deserializeobject

c#
小樊
92
2024-07-30 15:06:10
栏目: 编程语言

在C#中,可以使用Json.NET库来自定义反序列化对象。下面是一个简单的例子:

using Newtonsoft.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class CustomDeserializer : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Person);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jObject = JObject.Load(reader);

        Person person = new Person();
        person.Name = jObject.GetValue("name").ToString();
        person.Age = jObject.GetValue("age").Value<int>();

        return person;
    }

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

class Program
{
    static void Main()
    {
        string json = "{\"name\":\"John\",\"age\":30}";

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Converters.Add(new CustomDeserializer());

        Person person = JsonConvert.DeserializeObject<Person>(json, settings);

        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
    }
}

在上面的例子中,我们定义了一个自定义的JsonConverter类CustomDeserializer,用于反序列化Person对象。在ReadJson方法中,我们手动提取json中的数据并创建一个Person对象。然后将这个CustomDeserializer类添加到JsonSerializerSettings中,并传递给JsonConvert.DeserializeObject方法来实现自定义反序列化。

0