JavaScriptSerializer - 如何反序列化名称中带有破折号(“-”)的属性?
尝试反序列化这个JSON:
{
"result":"success"
"arguments": {
"activeTorrentCount":22,
"cumulative-stats": {
"downloadedBytes":1111,
}
}
}
我的类:
private class DeserializationMain
{
public string result; //works
public args arguments; //works, has deserialized activeTorrentCount
public class args
{
public int activeTorrentCount;
public current cumulative_stats; //doesn't work, equals null
public class current
{
public long downloadedBytes;
}
}
}
我猜cumulative-stats不会被反序列化,因为它在我的类中有cumulative_stats变量名,如何用破折号反序列化那个东西?
Trying to deserialize this JSON:
{
"result":"success"
"arguments": {
"activeTorrentCount":22,
"cumulative-stats": {
"downloadedBytes":1111,
}
}
}
My class:
private class DeserializationMain
{
public string result; //works
public args arguments; //works, has deserialized activeTorrentCount
public class args
{
public int activeTorrentCount;
public current cumulative_stats; //doesn't work, equals null
public class current
{
public long downloadedBytes;
}
}
}
I guess cumulative-stats doesn't get deserialized because it has cumulative_stats variable name in my class, how to deserialize that thing with a dash?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种替代方法是使用 DataContractJsonSerializer 而不是 JavascriptSerializer。
如果您像这样声明您的类:
您可以像这样反序列化它:
将产生:
累积统计.downloadedBytes:1111
One alternative is to use the DataContractJsonSerializer instead of the JavascriptSerializer.
If you declare your classes like this:
You can deserialize it like this:
Will produce:
Cumulative-stats.downloadedBytes: 1111
我认为大多数 JSON 序列化库都支持属性别名,例如自定义属性:
我的建议是,让 C# 代码保持标准 C# 编码约定并映射到 JSON 中的属性名称。
I think most of the JSON serialization libraries support alias for properties, like custom attribute:
My suggestion is, keep your C# code with standard C# coding conventions and mapping to the property name in JSON.