针对匿名对象的System.Text.Json序列化 [英] System.Text.Json serialization against an anonymous object

查看:360
本文介绍了针对匿名对象的System.Text.Json序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP .Net Core 3.1应用程序,使用2.2从另一个代码移植部分代码.到目前为止,我想从NewtonSoft JSON序列化库切换到新的System.Text.Json,但是我遇到了一些麻烦.

I'm working on an ASP .Net Core 3.1 application, porting part of the code from another using 2.2. So far, I'd like to switch from the NewtonSoft JSON serialization library to the new one, System.Text.Json, but I have some trouble.

考虑使用此返回类型为HTTP-GET服务提供服务的功能:

Consider a function to serve a HTTP-GET service with this returning type:

    [HttpGet("myservice")]
    public async Task<ActionResult<object>> GetDataAsync( ...

然后,最后一部分可以描述如下:

Then, the final part could be depicted as follows:

        var items = new List<IMyInterface>();
        int totalCount = ...
        int min = ...
        int max = ...

        return new ActionResult<object>(new
        {
            totalCount,
            min,
            max,
            items
        });

但是,它不起作用:items集合通过其声明的类型(IMyInterface)而不是实际的类型进行序列化.我在这里这里这是一种预期的行为,尽管对我而言不是那么直观.

However, it doesn't work: the items collection is serialized by its declared type (IMyInterface), instead of the actual type(s). I read here that this is an expected behavior, although not so intuitive to me.

我的问题是:是否有任何方便而可靠的方法来利用新的序列化程序甚至处理匿名对象?我会避免每次都可以内联编写结果时创建一个特定的对象.

My question is: is there any convenient yet reliable way to leverage the new serializer even dealing with anonymous objects? I would avoid to create a specific object every time I can compose the result inline.

更新:

这样做似乎可行,但看起来确实很丑:

doing this it seems to work, but it looks really ugly:

        return new ActionResult<object>(new
        {
            totalCount,
            min,
            max,
            items = items.Cast<object>()
        });

推荐答案

DotNetFiddler

如果要序列化对象,为什么不将它们初始化为对象?是否需要创建强类型?

If you want to serialize the objects, why not initialize them as objects? Is there a requirement to create it strong typed?

    public static void Test()
    {
        var items = new List<object>() { new Class1 { Foo = "foo1", Bar1 = "Bar1" }, new Class2 { Foo = "foo1", Bar2 = "Bar2" } };
        int totalCount = 1;
        int min = 2;
        int max = 3;


        var root = new
        {
            totalCount,
            min,
            max,
            items,
        };

        var json = JsonSerializer.Serialize<object>(root, new JsonSerializerOptions { WriteIndented = true, });

        Console.WriteLine(json);
    }

如果将项目创建为List<object>,则无需更改或执行任何操作.这可能是一种更清洁的方法,而不是在创建对象时将它们每个都强制转换为对象.

If you create the items as List<object>, you dont have to change or do anything. This might be a cleaner way instead of casting each of them to object at time of creating the object.

这篇关于针对匿名对象的System.Text.Json序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆