2016-09-27 31 views
0

我使用Newwtonsoft.JSON爲建立我的JSON文件,其實我所做的就是創建不同類型的模型,因爲這樣:如何使用不同的索引創建json?

class GeneralModel 
{ 
    public string Language { get; set; } 
} 

,然後構建JSON文件:

GeneralModel lsModel = new GeneralModel(); 
string json = JsonConvert.SerializeObject(lsModel); 
File.WriteAllText(settingsFilePath, json); 

這將創建一個包含Language一個JSON,但我需要把這個JSON不同的類,我需要的是建立一個包含每個類名的索引,例如:

"GeneralModel": { 
    "Language" : "english" 
}, 
"AnoherClassName": { 
    "ClassProperty" : value 
} 

我如何用Newtonsoft做到這一點?

+0

您展現對象的JSON數組。嘗試完全相同的代碼 - 創建一個'對象[]'數組與您想要的類,並序列化數組而不是單個對象 –

回答

1
public class GeneralModel 
{ 
    public string Language { get; set; } 
} 

public class AnotherModel 
{ 
    public string AnotherProperty { get; set; } 
} 

public class SuperClass 
{ 
    public GeneralModel generalModel { get; set; } 

    public AnotherModel anotherModel { get; set; } 
} 

然後

  SuperClass s = new WMITest.SuperClass(); 
      s.generalModel = new GeneralModel(); 
      s.generalModel.Language = "language"; 
      s.anotherModel = new AnotherModel(); 
       s.anotherModel.AnotherProperty = "example"; 
      string json = JsonConvert.SerializeObject(s); 
+0

是可能的設置另一個名稱,而不是通用模型在JSON沒有改變類名?我記得像屬性 – Unchained