Using Json.NET, deserialize to a property but has a numeric name

£可爱£侵袭症+ 提交于 2019-12-07 07:56:28

By far the simplest solution is to use a dictionary rather than an object:

public class neighbourhoodcrimes
{
    public String commentary { get; set; }
    public Dictionary<string, month> crimes { get; set; }
}

Alternatively, if you want to, you can provide a name explicitly:

public class crimes
{
    [JsonProperty("2010-12")]
    public month _2010_12 { get; set; }
}

Alternatively again, if you can get restsharp to use a JsonSerializer you provide to it, you can do the name re-mapping generically:

var serializer = new JsonSerializer { ContractResolver = new HyphenContractResolver() };
using (var reader = new JsonTextReader(new StringReader(TestData2)))
{
    var crimes = serializer.Deserialize<neighbourhoodcrimes>(reader);
    ...
}

class HyphenContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
    protected override string ResolvePropertyName(string propertyName)
    {
        return propertyName.TrimStart('_').Replace('_', '-');
    }
}

But in this case, that breaks category.crime_rate by remapping it to crime-rate as well, which it doesn't let you override with JsonProperty. Perhaps this is solvable with a lower level implementation of IContractResolver, but that gets really hairy really fast. And then there's implementing JsonConvert, but that can be even more hairy.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!