我之前遇到过这个问题,在这里我创建了一个数据模型,该模型稍后将被序列化为JSON字符串,但是我希望包含属性的类也被序列化。请参阅以下示例:
我有我的数据模型:
public class MyModel
{
[JsonProperty(PropertyName = "Prop1")]
public string Property1 { get; set; }
[JsonProperty(PropertyName = "Prop2")]
public string Property2 { get; set; }
}
然后将其序列化为:
{
"Prop1":"Some Value",
"Prop2":"Some Value"
}
有没有一种方法可以使它序列化为:
{
"MyModel":
{
"Prop1":"Some Value",
"Prop2":"Some Value"
}
}
我目前正在做的似乎根本不合适的事情是为我的JSON创建包装对象的东西:
string object = @"{""ticket"":" + JsonConvert.SerializeObject(model) + @"}"
我可以在类中添加某种属性吗?
[SerializeThisClass, ProperName="MyModel"]
public class MyModel
{
[JsonProperty(PropertyName = "Prop1")]
public string Property1 { get; set; }
[JsonProperty(PropertyName = "Prop2")]
public string Property2 { get; set; }
}
JsonConvert.SerializeObject( new{ MyModel = model})
应该可以
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句