Multiple names for a single property when deserializing

Oct 17, 2012 at 6:04 AM
Edited Oct 17, 2012 at 6:06 AM

I've searched around a bit and looked at the documentation but I don't think this is possible unless I'm missing something.

The best way to explain this is with an example.

Lets say I have some simple class

[JsonObject]
public class Person
{
    [JsonProperty]
    public string Name { get; set; }

    [JsonProperty]
    public string PhoneNumber { get; set; }
}

Now let's say I don't really care about serialization, only deserialization and that I'm obtaining data from multiple providers. In general, the format of the json obtained from the multiple sources is in the same format (i.e. A person always has a name and phone number) but one source uses "phonenumber" and another just uses "phone" or "number".

Is there any way I could indicate that either "phonenumber", "phone", or "number" are all valid entries that map to the PhoneNumber property? For example something like this would be nice:

[JsonObject]
public class Person
{
    [JsonProperty]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "PhoneNumber", Aliases="Phone, Number")]
    public string PhoneNumber { get; set; }
}

Any ideas? Possibly a feature request :)

Oct 17, 2012 at 1:52 PM
Edited Oct 17, 2012 at 1:52 PM

How about specifying all possible properties?

[JsonObject]
public class Person
{
    [JsonProperty]
    public string PhoneNumber { get; set; }

    [JsonProperty]
    public string Phone { get { return PhoneNumber; } set { PhoneNumber = value; } }
// ...
}

Oct 18, 2012 at 3:46 AM
Edited Oct 18, 2012 at 3:46 AM

I guess that works but it seems a bit hacky to add a bunch of properties. I would make them private so the object only exposes PhoneNumber.

Thanks for the suggestion. 

[JsonObject]
public class Person
{
    [JsonProperty]
    public string Name { get; set; }

    [JsonProperty]
    public string PhoneNumber { get; set; }

    [JsonProperty]
    private string Phone 
    { 
        get { return this.PhoneNumber; }
        set { this.PhoneNumber = value; }
    }
}
Oct 18, 2012 at 4:10 AM

Thinking about this more, the other reason I don't like this is if I wanted to use this class for serialization at some point, the output would have all these duplicates instead of just the one I want "PhoneNumber".

Jan 20, 2015 at 3:17 PM
+1. I would love support for this. I need easier ways to rename properties but still support reading in the old data. I would also like the ability to rename an enumeration value but keep the old enum value name as an alias.
Mar 10, 2015 at 6:09 PM