假设我有这个对象:
[JsonObject]
public class User
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "birthday")]
public DateTime Birthday { get; set; }
}
这将生成如下 JSON:
{
"id":null,
"name":"Bob",
"birthday":"/Date(374479200000-0600)/"
}
我正在寻找一种方法来添加类名,例如:
{
"user":{
"id":null,
"name":"Bob",
"birthday":"/Date(374479200000-0600)/"
}
}
JSON.NET 有办法做到这一点吗?谢谢!
编辑
我这样做的原因是将 .NET 客户端连接到 Rails Web 服务。 Rails 将模型的属性放在命名空间下,因此我正在寻找一种让 .NET 符合这一点的方法。
但是,在阅读了一些关于 Backbone.js 的内容之后,看起来一个可能的替代方案是在 Rails 中禁用此行为:
If you're working with a Rails backend, you'll notice that Rails' default to_json implementation includes a model's attributes under a namespace. To disable this behavior for seamless Backbone integration, set:
ActiveRecord::Base.include_root_in_json = false
最佳答案
如果您只想对根对象执行此操作,我认为最简单的方法就是按照您想要的方式序列化对象:
static object AddTypeName(object o)
{
return new Dictionary<string, object>
{
{ o.GetType().Name.ToLowerInvariant(), o }
};
}
关于c# - 将对象名称添加到其序列化字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8898747/