Skip to content

JSON source generator fails to compile if context type isn't in a namespace #56920

@stephentoub

Description

@stephentoub

This fails to compile:

using System;
using System.Text.Json.Serialization;

class Program
{
    public static void Main() { }
}

internal class Book
{
    public string? Name { get; set; }
}

[JsonSerializable(typeof(Book))]
internal partial class MyJsonContext : JsonSerializerContext { }

with the errors:

Error	CS0534	'MyJsonContext' does not implement inherited abstract member 'JsonSerializerContext.GetTypeInfo(Type)'
Error	CS7036	There is no argument given that corresponds to the required formal parameter 'instanceOptions' of 'JsonSerializerContext.JsonSerializerContext(JsonSerializerOptions?, JsonSerializerOptions?)'

but wrap both the type to be serialized and the context type in a namespace, and then it compiles fine:

using System;
using System.Text.Json.Serialization;

class Program
{
    public static void Main() { }
}

namespace Anything
{
    internal class Book
    {
        public string? Name { get; set; }
    }

    [JsonSerializable(typeof(Book))]
    internal partial class MyJsonContext : JsonSerializerContext { }
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions