Skip to content

Should serialize avoid emitting metadata on types that are unsupported on deserialize? #1881

@jozkee

Description

@jozkee

Today, we only emit metadata to reference types and we avoid doing it for value types, but there are a few reference types that are unsupported on deserialization, mostly because they have the special behavior of temporarily storing its elements on an enumerable.

An example of those types are:

  • T[]
  • ImmutableDictionary<TKey, TValue>

You cannot deserialize with preserve semantics into these types therefore they are unable to round trip.

public static void RoundTripArray()
{
    string[] words = new string[] { "apple", "banana", "cherry" };

    var opts = new JsonSerializerOptions
    {
        ReferenceHandling = ReferenceHandling.Preserve
    };

    string json = JsonSerializer.Serialize(words, opts);
    /* serialized words:
    {
        "$id": "1",
        "$values": [
            "apple",
            "banana",
            "cherry"
        ]
    }*/
    string[] wordsCopy = JsonSerializer.Deserialize<string[]>(json, opts);
}

Running above sample throws the following example on JsonSerializer.Deserialize:

Cannot parse a JSON object containing metadata properties like '$id' into an array or immutable collection type. Type 'System.String[]'.

Alternatively we can do one the following options to avoid the round-trip issue:

  • Avoid emitting metadata for these unsupported types (as suggested in the title).
  • Throw when an unsupported type is attempted to be serialized.
  • On deserialize try to "eat up" or ignore the metadata semantics (but still validate that they are correctly formatted, as we do for struct objects?).

cc @ahsonkhan, @layomia, @steveharter

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions