使用Json.NET,反序列化为属性但具有数字名称

时间:2011-02-25 13:06:14

标签: json.net

得到了Json

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

}}“

使用Json.net对其进行反序列化,以及使用json.net的restsharp。但它不会映射到我的类,因为我不能放置一个名为2010-12的属性,因为.net框架不允许这样做。

有什么想法吗?

目前我得到了

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 个答案:

答案 0 :(得分:3)

到目前为止,最简单的解决方案是使用字典而不是对象:

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

或者,如果您愿意,可以明确提供名称:

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

或者再次 ,如果你可以通过restsharp使用你提供给它的JsonSerializer,你可以进行名称重新映射:

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('_', '-');
    }
}

但是在这种情况下,通过将category.crime_rate重新映射到crime-rate会导致JsonProperty中断,而不允许您使用IContractResolver覆盖JsonConvert。也许这可以通过较低级别的{{1}}实现来解决,但这真的很快就会变得毛茸茸。然后是实施{{1}},但这可能会更加毛茸茸。