Skip to content

Provide option for the serializer to treat IEnumerables like objects with members #1808

Closed
@vbelinschi

Description

@vbelinschi

If I have a similar class:

public class MyEnumerable : IEnumerable<string>
    {
        public int Doing { get; set; }
        public IList<string> Stuff { get; set; }

        public IEnumerator<string> GetEnumerator()
        {
            return Stuff.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

The result of the serialization will be just the values of Stuff.
Fx.:

var my = new MyEnumerable();
my.Stuff = new List<string> { "one", "two" };
my.Doing = 3;
var json = System.Text.Json.JsonSerializer.Serialize(my);

the result is: ["one","two"].
The Doing member is ingored. So the expected result would be: {"Doing":3,"Stuff":["one","two"]}.

In Newtonsoft.JSON I can use [JsonObject] attribute, to enforce the serialization of all the members.

Is there something similar in System.Text.Json? And if not, is there plan to implement it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions