System.Text.Json serialization against an anonymous object

你说的曾经没有我的故事 提交于 2020-01-24 18:36:12

问题


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.

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
        });

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.

UPDATE:

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

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

回答1:


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);
    }

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.



来源:https://stackoverflow.com/questions/59581708/system-text-json-serialization-against-an-anonymous-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!