svenheden / csharp-models-to-typescript

C# models to TypeScript
89 stars 58 forks source link

JsonIgnoreAttribute.Condition is not handled #62

Open r-pankevicius opened 2 years ago

r-pankevicius commented 2 years ago

Both classic Newtonsoft.Json and System.Text.Json have JsonIgnoreAttribute to prevent properties from being Json-serialized. However Newtonsoft's JsonIgnore is unconditional: if public property is marked with it, it's not in Json output.

Microsoft's JsonIgnore has Condition property to control more aspects. Only Always which is default value shall not produce no TypeScript property in generated output while 3 other enum values should.

r-pankevicius commented 2 years ago

Quick'n'dirty fix in ModelCollector.cs would fix the issue rewriting IsIgnored method:

private static bool IsIgnored(SyntaxList<AttributeListSyntax> propertyAttributeLists) =>
    propertyAttributeLists.Any(attributeList =>
        attributeList.Attributes.Any(attribute => ShouldBeJsonIgnored(attribute)));

private static bool ShouldBeJsonIgnored(AttributeSyntax attribute)
{
    if (!attribute.Name.ToString().Equals("JsonIgnore"))
        return false;

    if (attribute.ArgumentList == null)
        return true; // Plain [JsonIgnore]

    foreach (var argument in attribute.ArgumentList.Arguments)
    {
        string argString = argument.ToString();
        // E.g. "Condition = JsonIgnoreCondition.Never"
        if (argString.StartsWith("Condition"))
        {
            return argString.EndsWith("Always");
        }
    }

    return true;
}

Used argument.ToString() and did string parsing because I have not enough experience with Microsoft.CodeAnalysis.CSharp.Syntax.