C# 将JSON对象包装到另一个对象中的正确方法是什么?
我以前遇到过这个问题,我创建了一个数据模型,稍后将序列化为JSON字符串,但我希望包含属性的类也被序列化。请参见下面的示例: 我有我的数据模型:C# 将JSON对象包装到另一个对象中的正确方法是什么?,c#,json,C#,Json,我以前遇到过这个问题,我创建了一个数据模型,稍后将序列化为JSON字符串,但我希望包含属性的类也被序列化。请参见下面的示例: 我有我的数据模型: public class MyModel { [JsonProperty(PropertyName = "Prop1")] public string Property1 { get; set; } [JsonProperty(PropertyName = "Prop2")] public string Propert
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"
}
}
有没有办法让它序列化为:
{
"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; }
}
添加另一个将MyModel作为其成员的类,然后序列化父类
public class Parent
{
[JsonProperty(PropertyName = "MyModel")]
public MyModel MyModel { get; set; }
}
你可以用这个来实现
public class MyModel
{
[JsonProperty(PropertyName = "Prop1")]
public string Property1 { get; set; }
[JsonProperty(PropertyName = "Prop2")]
public string Property2 { get; set; }
}
public class Wrapper{
[JsonProperty(PropertyName = "MyModel")]
public MyModel myModel{get;set;}
}
然后序列化包装器对象
JsonConvert.SerializeObject( new{ MyModel = model})
应该可以使用JsonConvert.SerializeObject(新的{MyModel=model});这将创建一个具有简单属性MyModel的匿名对象。