Newtonsoft.json: Make JsonPropertyAttribute allow multiple usages on same property

Created on 24 Feb 2018  路  1Comment  路  Source: JamesNK/Newtonsoft.Json

Hi,

I need to deserialize a series of documents that are almost similar but might change few details.

I was hoping to spare myself the need of creating multiple classes by decorating the same target property with more instances of the JsonPropertyAttribute but this is not possible.

Ideally it would be nice to be able to do something like

public class ResultList<T>
{
    [JsonProperty("items")]
    [JsonProperty("values")]
    [JsonProperty("results")]
    public IReadOnlyList<T> Items { get; set; }

    [JsonProperty("hasMore")]
    [JsonProperty("has-more")]
    public bool HasMore { get; set; }

    [JsonProperty("offset")]
    public long? Offset { get; set; }
}

Since most of the time this happens when deserializing a result list, the ambiguity introduced when serializing wouldn't a big issue. In that case, picking the value of the first attribute found would be good enough.

Most helpful comment

A simple solution which does not require a converter: just add a second, private property to your class, mark it with [JsonProperty("name2")], and have it set the first property:

public class Specifications
{
[JsonProperty("name1")]
public string CodeModel { get; set; }

[JsonProperty("name2")]
private string CodeModel2 { set { CodeModel = value; } }

}

Ref
https://stackoverflow.com/questions/43714050/multiple-jsonproperty-name-assigned-to-single-property

>All comments

A simple solution which does not require a converter: just add a second, private property to your class, mark it with [JsonProperty("name2")], and have it set the first property:

public class Specifications
{
[JsonProperty("name1")]
public string CodeModel { get; set; }

[JsonProperty("name2")]
private string CodeModel2 { set { CodeModel = value; } }

}

Ref
https://stackoverflow.com/questions/43714050/multiple-jsonproperty-name-assigned-to-single-property

Was this page helpful?
0 / 5 - 0 ratings