Barry
Barry

Reputation: 11

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

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; }
}

Upvotes: 1

Views: 1468

Answers (1)

Simon Buchan
Simon Buchan

Reputation: 13245

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.

Upvotes: 3

Related Questions