使用Json.NET,反序列化为属性,但具有数字名称 [英] Using Json.NET, deserialize to a property but has a numeric name
问题描述
得到了杰森
{
"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框架不允许这样做.
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.
有什么想法吗?
目前我知道了
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; }
}
推荐答案
到目前为止,最简单的解决方案是使用字典而不是对象:
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; }
}
或者再次 ,如果您可以让restsharp使用提供给它的JsonSerializer
,则可以通用地进行名称重新映射:
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('_', '-');
}
}
但是在这种情况下,它也会通过将category.crime_rate
映射到crime-rate
来破坏它,这不允许您使用JsonProperty
覆盖它.使用IContractResolver
的较低级别的实现,也许可以解决此问题,但这确实非常耗时.然后实现了JsonConvert
,但这可能更加麻烦.
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.
这篇关于使用Json.NET,反序列化为属性,但具有数字名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!