使用各种属性反序列化JSON

时间:2018-09-28 14:18:20

标签: c# json json.net

我有一个具有

等各种属性的json
{
   "userFirstName":"John",
   "userLastName":"Doe",
   "userDefined-prop1":"value1",
   "userDefined-prop2":"value2",
   "userDefined-prop3":"value3"
}

我想在这样的类中反序列化它们,其中UserDefined字典将包含

这样的对
{ "prop1" : "value1", "prop2" : "value2", "prop3" : "value3"}

代码:

class User
{
    [JsonProperty("userFirstName")]
    public string Name { get; set; }

    [JsonProperty("userLastName")]
    public string LastName{ get; set; }

    [JsonProperty("userDefined")]
    public Dictionary<string, string> UserDefined { get; set; }
}

我想知道如何进行映射。也许有类似[JsonPropery("userDefined-*")][JsonPropery("userDefined-[key]")]的东西吗?

1 个答案:

答案 0 :(得分:0)

我很感激Kalten,这正是我所寻找的!我的最后一堂课看起来像

public class User
{
    [JsonProperty("userFirstName")] public string Name { get; set; }

    [JsonProperty("userLastName")] public string LastName { get; set; }

    [JsonExtensionData] Dictionary<string, JToken> _userDefined;

    public Dictionary<string, string> UserDefined => _userDefined.ToDictionary(x => x.Key.Replace("userDefined-", string.Empty), x => x.Value.ToString());
}