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

老子叫甜甜 提交于 2019-12-10 11:43:58

问题


Got the Json

{    
"commentary": null,     
"crimes": 
    {        
    "2010-12": 
        {            
        "anti-social-behaviour": 
            {                
            "crime_rate": "0.08",                 
            "crime_level": "below_average",                 
            "total_crimes": 47 
            }
        }
    }

}}"

Using Json.net to deserialize it, well restsharp which uses json.net. but it wont map to my classes as I cannot put a property called 2010-12 as the .net framework does not allow this.

Any thoughts?

Currently i got

public class neighbourhoodcrimes
{
    public String commentary { get; set; }
    public crimes crimes { get; set; }
}

public class crimes
{
    public month _2010_12 { get; set; }
}

public class month
{

    public category anti_social_behaviour { get; set; }
    public category other_crime { get; set; }
    public category all_crime { get; set; }
    public category robbery { get; set; }
    public category burglary { get; set; }
    public category vehicle_crime { get; set; }
    public category violent_crime { get; set; }

}

public class category
{

    public String crime_rate { get; set; }
    public String crime_level { get; set; }
    public String total_crimes { get; set; }
}

回答1:


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.



来源:https://stackoverflow.com/questions/5117586/using-json-net-deserialize-to-a-property-but-has-a-numeric-name

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