【问题标题】:JsonSerializer.Deserialize: Deserialize object to its actual typeJsonSerializer.Deserialize:将对象反序列化为其实际类型
【发布时间】:2022-11-16 13:47:56
【问题描述】:

我正在将一个 JSON 列表反序列化为 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

有没有办法以某种方式将确切的类型编码到序列化文本中?

【问题讨论】:

标签: c# json serialization typing system.text.json


【解决方案1】:

是的。您只需为要序列化/反序列化的对象创建一个 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);

【讨论】:

  • 不,正如我所说,我必须使用 object[],无法知道列表元素的类型......
  • 听起来您正在尝试访问JsonElement ValueKind,这里是另一个answer,这可能就是您要查找的内容
【解决方案2】:

这是一个快速的肮脏解决方案。您可以将其用作原型来进一步开发您自己的作品。非原始类型的类型名称是通过匿名类和硬编码的属性名称添加的,这是脏的部分。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2022-12-19
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多