2015-06-24 13 views
6

Daha önce bir JSON dizesine serileştirilecek bir veri modeli oluşturduğum bu soruna daha önce girdim, ancak özellikleri içeren sınıfın da serileştirilmesini istiyorum.JSON nesnesini başka bir nesneye sarmanın doğru yolu nedir?

public class MyModel 
{ 
    [JsonProperty(PropertyName = "Prop1")] 
    public string Property1 { get; set; } 

    [JsonProperty(PropertyName = "Prop2")] 
    public string Property2 { get; set; } 
} 

sonra serialize ediyorum: benim veri modeli var

: Aşağıdaki örneğe bakın ben serialize yapabilir bir yolu var mı

{ 
    "Prop1":"Some Value", 
    "Prop2":"Some Value" 
} 

için:

{ 
    "MyModel": 
    { 
     "Prop1":"Some Value", 
     "Prop2":"Some Value" 
    } 
} 

Şu anda yapmakta olduğum şey şu anlama gelmiyor ki m için bir sarma nesnesi oluşturmak gibi y JSON:

string object = @"{""ticket"":" + JsonConvert.SerializeObject(model) + @"}"

ben gibi benim sınıf bir şeye ekleyebileceğiniz özelliğin çeşit var:

[SerializeThisClass, ProperName="MyModel"] 
public class MyModel 
{ 
    [JsonProperty(PropertyName = "Prop1")] 
    public string Property1 { get; set; } 

    [JsonProperty(PropertyName = "Prop2")] 
    public string Property2 { get; set; } 
} 
+2

Kullanım JsonConvert.SerializeObject olması gerektiğini elde edebilir (yeni {MyModel = modeli}) ; Bu, MyModel adlı basit bir özellik ile anonim bir nesne oluşturur. –

cevap

9
JsonConvert.SerializeObject(new{ MyModel = model}) 

Tamam

1

sonra ebeveyn serialize onun üyesi olarak MyModel olan başka bir sınıf ekleyin.

public class Parent 
{ 
    [JsonProperty(PropertyName = "MyModel")] 
    public MyModel MyModel { get; set; } 

} 
0

bu

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;} 
} 

sonra Sarıcı nesne seri ile

İlgili konular