C# JSON Derialization - single class for any property name

时间:2017-11-08 22:05:12

标签: c# json

I have the following classes that the JSON (which will follow) can deserialize into:

public partial class Root
{
    [JsonProperty("entries")]
    public NestedStatEntries Entries { get; set; }
}

public partial class NestedStatEntries
{
    [JsonProperty("activeMemberCnt")]
    public LongValue ActiveMemberCnt { get; set; }
}

public class LongValue
{
    [JsonProperty("value")]
    public long Value { get; set; }
}

JSON:

{
    "entries": {
        "activeMemberCnt": {
            "value": 0
        }
    }
}

I want to be able to use that same LongValue wrapper class for similar JSON responses that would have just a single value that's an integer as below, put perhaps, instead of "value", the key would be something like "metric".

Other JSON:

{
    "entries": {
        "activeMemberCnt": {
            "metric": 0
        }
    }
}

Is there a way to remove the [JsonProperty("value")] from LongValue, and dynamically set it from outside this class, so that I can re-use that same object for responses that have the same value type, but a key, such as the one above?

1 个答案:

答案 0 :(得分:1)

只需将 NestedStatEntries 声明更改为

即可
public partial class NestedStatEntries
{
    [JsonProperty("activeMemberCnt")]
    public Dictionary<string,long> ActiveMemberCnt { get; set; }
}

previous question

相似的字典技巧