Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonIgnoreAttribute.Condition is not handled #62

Open
r-pankevicius opened this issue Aug 30, 2022 · 1 comment
Open

JsonIgnoreAttribute.Condition is not handled #62

r-pankevicius opened this issue Aug 30, 2022 · 1 comment

Comments

@r-pankevicius
Copy link

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
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant