Arieleo
Arieleo

Reputation: 409

How can I parse a JSON file with references in a .NET Native AOT project?

Deserializing JSON files using System.Text.Json in a Native AOT project requires the source generation API, which takes a JsonSerializerContext object. I've managed that.

Now it appears that the JSON files I need to parse can include references. Here's a simplified example:

{
    "definitions": {
        "someProperty": {
            "type": "string"
        }
    },
    "properties": {
        "$ref": "#/definitions"
    }
}

According to Microsoft, to support this I need feed the deserializer with the option to preserve references, using a the ReferenceHandler property of JsonSerializerOptions object.

I didn't see any JsonSerializer.Deserialize() overload which takes both a JsonSerializerOptions and a JsonSerializerContext, and this led me to discover that with source generation, the options should be set as an attribute on the context instead of provided as a call argument – like so:

[ JsonSourceGenerationOptions( WriteIndented = true ) ]
[ JsonSerializable( typeof( SomeType ) ) ]
    
public partial class InterestingTypeSourceGenerationContext: JsonSerializerContext
{
}

The problem is that this attribute, JsonSourceGenerationOptionsAttribute, does not have the ReferenceHandler property mentioned in the article, that JsonSerializerOptions does.

How then, do I parse references when using the source generation API?

Upvotes: 1

Views: 302

Answers (0)

Related Questions