Compiler error when duplicate JsonProperty names

w230769's Avatar


08 Jun, 2018 03:02 PM


I have seen some samples where the compiler is used to throw errors when an annotation is missing, can it be used to test for duplicate annotations.
In my case, I have to obfuscate the code and the properties get some name (I have no control over the name and no backward compatibility is guaranteed)
We have therefore had a convention to use abbreviated property names, so FileName could become A1 and the 2nd property becomes some other letter[number] code (A0..Z9)

So we would set the 7th property to [JsonProperty("A7")]
We read them using the populate method leaving the defaults of the new properties that have not been serialized before.
JsonConvert.PopulateObject(File.ReadAllText(_filename), this);

When properties get added (or removed) this starts to become an issue, it would be cool if we could generate a compiler error when a duplicate is assigned as one can remember what was added if a compiler error occurs.

Do you have any samples for me to use?

Kind regards


  1. Support Staff 1 Posted by PostSharp Techn... on 12 Jun, 2018 04:18 PM

    PostSharp Technologies's Avatar


    we currently don't have any similar samples, but the following should demonstrate how to solve this issue:

    public class TestValidator : TypeLevelAspect
        public override bool CompileTimeValidate(Type type)
            HashSet<string> propertyNames = new HashSet<string>();
            foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)property.GetCustomAttribute(typeof(JsonPropertyAttribute));
                if (jsonProperty == null)
                if (!propertyNames.Add(jsonProperty.PropertyName))
                    Message.Write(property, SeverityType.Error, "A01", "Duplicate JSON property {0} specified on {1}.",
                        jsonProperty.PropertyName, property);
            return false;

    I hope it helps.

    Best regards,

  2. w230769 closed this discussion on 13 Jun, 2018 06:17 AM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts


? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac