JsonSerializer.Deserialize:将对象反序列化为其实际类型

ifsvaxew  于 2022-11-19  发布在  其他
关注(0)|答案(2)|浏览(181)

我正在将一个JSON列表反序列化为object[],并期望得到一个object数组。但是我想反序列化为更具体的类型。有没有办法做到这一点,可能是在序列化时提供确切的类型?不幸的是,我不能在我的代码中比object[]更具体...

using System.Text.Json;

namespace Tests.DeSerialize;

class Program
{
    public static void Main(string[] args)
    {
        object[] objs = new object[]{
            42,
            "foobar",
            false,
            new Example {
                Name = "example",
            }
        };
        foreach (var obj in objs)
        {
            Console.WriteLine(obj.GetType().Name);
        }

        var serialized = JsonSerializer.Serialize(objs);
        Console.WriteLine();
        Console.WriteLine(serialized);
        Console.WriteLine();

        object[] deSerializedObjs = JsonSerializer.Deserialize<object[]>(serialized);
        foreach (var obj in deSerializedObjs)
        {
            Console.WriteLine(obj.GetType().FullName);
        }
    }
}

public class Example
{
    public string Name { get; set; }

    public override string ToString() => $"{GetType().Name}(\"{Name}\")";
}

输出量:

Int32
String
Boolean
Example

[42,"foobar",false,{"Name":"example"}]

System.Text.Json.JsonElement
System.Text.Json.JsonElement
System.Text.Json.JsonElement
System.Text.Json.JsonElement

是否有办法将确切的类型编码到序列化文本中?

huwehgph

huwehgph1#

是的。您只需要为要序列化/反序列化的对象创建一个C#类。

// you can use more meaningful names for the classes/variables
public class Object
{
   public int MyInt { get; set; }
   public string MyStr { get; set; }
   public bool MyBool { get; set; }
   public Example Example{ get; set; }
}

public class Example
{
   public string Name { get; set; }
   // other variables that might be in the Example object
}

序列化对象的工作原理应该是一样的,但在反序列化时,您需要做一些小的更改:

// use the public class name and if expecting an array use a collection such as List
var deSerializedObjs = JsonSerializer.Deserialize<List<Object>>(serialized);
vvppvyoh

vvppvyoh2#

这里有一个快速的脏的解决方案。你可以用它作为原型来进一步开发你自己的作品。非基元类型的类型名是通过匿名类和硬编码的属性名添加的,这是脏的部分。

using System.Text.Json;

namespace Tests.DeSerialize;

class Program
{
    public static void Main(string[] args)
    {

        object[] objs = new object[]{
            42,
            "foobar",
            false,
            new {
                Type = "Tests.DeSerialize.Example",
                Value = new Example{
                    Name = "example"
                }
            }
        };

        foreach (var obj in objs)
        {
            Console.WriteLine(obj.GetType().Name);
        }

        var serialized = JsonSerializer.Serialize(objs);
        Console.WriteLine();
        Console.WriteLine(serialized);
        Console.WriteLine();

        var deSerializedObjs = JsonSerializer.Deserialize<JsonElement[]>(serialized);
        foreach (var obj in deSerializedObjs)
        {
            Console.WriteLine(obj.MyDeserialize().GetType().FullName);
        }
    }
}

public static class JsonElementExtension
{
    public static Object MyDeserialize(this JsonElement jsonElement)
    {
        switch (jsonElement.ValueKind)
        {
            case JsonValueKind.String:
                return jsonElement.Deserialize(typeof(string));

            case JsonValueKind.Number:
                return jsonElement.Deserialize(typeof(int));

            case JsonValueKind.False:
            case JsonValueKind.True:
                return jsonElement.Deserialize(typeof(bool));

            case JsonValueKind.Array:
                return jsonElement.Deserialize(typeof(Array));

            case JsonValueKind.Object:

                return jsonElement.GetProperty("Value").Deserialize(Type.GetType(jsonElement.GetProperty("Type").GetString()));

            default:
                return jsonElement.Deserialize(typeof(object));
        }
    }
}

输出量:

Int32
String
Boolean
<>f__AnonymousType0`2

[42,"foobar",false,{"Type":"Tests.DeSerialize.Example","Value":{"Name":"example"}}]

System.Int32
System.String
System.Boolean
Tests.DeSerialize.Example

相关问题