RicoSuter / NJsonSchema

JSON Schema reader, generator and validator for .NET
http://NJsonSchema.org
MIT License
1.37k stars 529 forks source link

NJsonSchema generated code throwing The JSON value could not be converted #1687

Closed csmorley closed 5 months ago

csmorley commented 5 months ago

I am using NJsonSchema on the schema https://csrc.nist.gov/schema/nvd/api/2.0/cve_api_json_2.0.schema and it is throwing an error on deserializing:

System.Text.Json.JsonException: 'The JSON value could not be converted to
Model.CvssV30Type. Path: $.vulnerabilities[0].cve.metrics.cvssMetricV30[0].type

The following json snippet, specifically the type":"Primary" is the byte number for the above error:

metrics":{"cvssMetricV30":[{"source":"nvd@nist.gov","type":"Primary","cvssData":{"version":"3.0","vectorString":"CVSS:3.0\/AV:N\/AC:L\/PR:N\/UI:N\/S:U\/C:H\/I:H\/A:H","attackVector":"NETWORK",

With the generated POCO that has a property:

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
public partial record Metrics
{
    [System.Text.Json.Serialization.JsonPropertyName("cvssMetricV31")]
    public System.Collections.Generic.ICollection<CvssV31> CvssMetricV31 { get; set; }

    [System.Text.Json.Serialization.JsonPropertyName("cvssMetricV30")]
    public System.Collections.Generic.ICollection<CvssV30> CvssMetricV30 { get; set; }

    [System.Text.Json.Serialization.JsonPropertyName("cvssMetricV2")]
    public System.Collections.Generic.ICollection<CvssV2> CvssMetricV2 { get; set; }
}

Of type:

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
public enum CvssV30Type
{
    [System.Runtime.Serialization.EnumMember(Value = @"Primary")]
    Primary = 0,
    [System.Runtime.Serialization.EnumMember(Value = @"Secondary")]
    Secondary = 1,
}

It seems not to know how to convert the enum, what am i missing please?

To add, it seems this is only an issue when using JsonLibrary = CSharpJsonLibrary.SystemTextJson as with the below NewtonsoftJson it deserializes ok:

var schema = await JsonSchema.FromUrlAsync("https://csrc.nist.gov/schema/nvd/api/2.0/cve_api_json_2.0.schema");
var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings
{
    ClassStyle = CSharpClassStyle.Poco,
    JsonLibrary = CSharpJsonLibrary.NewtonsoftJson,
    Namespace = "Model"
}
csmorley commented 5 months ago

Was missing JsonStringEnumConverter:

var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter());
var other = System.Text.Json.JsonSerializer.Deserialize<Schema>(response.Content, options);