2013-04-09 43 views
0

追加到JSON對象,我需要序列化JSON對象,看起來像這樣:使用JSON.net

{ 
    "Documents": [ 
     { 
     "Title": "", 
     "DatePublished": "", 
     "DocumentURL": "", 
     "ThumbnailURL": "", 
     "Abstract": "", 
     "Sector": "", 
     "Country": [ 
      "", "", "" 
     ], 
     "Document Type": "" 
     } 
    ] 
} 

我在做什麼是從SQL Server結果獲取數據並存儲到像一個對象這樣的:

public List<Dictionary<string, string>> GetResults() 
{ 
    int index = 0; 
    while (this.myReader.Read()) 
    { 

     this.dataFrmDb = new Dictionary<string, string>(); 
     for (int i = 0; i < myReader.FieldCount; i++) 
     { 
      if (myReader.GetName(i) == "Country") 
      { 
       string[] delimiter = { " _qfvcq_ " }; 
       string text = myReader[myReader.GetName(i)].ToString(); 
       string[] results = text.Split(delimiter, StringSplitOptions.None); 

       //This list stores the values for "Country". 
       List<string> countries = new List<string>(); 
       for (int j = 0; j < results.Count(); j++) 
       { 
        countries.Add(results[j].ToString()); 
       } 
      } 
      else 
      {       
       this.dataFrmDb.Add(myReader.GetName(i), 
          myReader[myReader.GetName(i)].ToString()); 
      } 
     } 

     this.dictList.Add(this.dataFrmDb); 
    } 
    return this.dictList; 
} 

我然後將這些數據序列是這樣的:

Database connect = new Database(
    System.Configuration.ConfigurationManager.AppSettings["DatabaseConnectionString"], 
    System.Configuration.ConfigurationManager.AppSettings["StoredProcedure"]); 

List<Dictionary<string, string>> dataResults = connect.GetResults();   

Dictionary<string, List<Dictionary<string, string>>> myList = 
      new Dictionary<string, List<Dictionary<string, string>>>(); 

myList.Add("Documents", dataResults); 

string ans = JsonConvert.SerializeObject(myList, Formatting.Indented); 
System.Console.WriteLine(ans); 

獲得正確的outpu但如果你想看看原始的JSON格式,「國家」需要有多個值。我不知道如何將它實現到這個JSON對象中。如何使用JSON.net將「Country」值添加到JSON對象中?還有另外一種方法可以解決這個問題嗎?

回答

2

如果更改dataFrmDbDictionary<string, object>代替Dictionary<string, string>,那麼你可以存儲這些國家像其他價值一樣列入其中。然後Json.Net會像你想要的那樣序列化它。

下面是一個例子程序這表明:

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<Dictionary<string, object>> dataResults = GetResults();   
     Dictionary<string, List<Dictionary<string, object>>> myList = 
         new Dictionary<string, List<Dictionary<string, object>>>(); 
     myList.Add("Documents", dataResults); 
     string ans = JsonConvert.SerializeObject(myList, Formatting.Indented); 
     System.Console.WriteLine(ans); 
    } 

    public static List<Dictionary<string, object>> GetResults() 
    { 
     List<Dictionary<string, object>> dictList = new List<Dictionary<string, object>>(); 

     Dictionary<string, object> dataFrmDb = new Dictionary<string, object>(); 
     dataFrmDb.Add("Title", "An Example Document"); 
     dataFrmDb.Add("DatePublished", DateTime.Now.ToString()); 
     dataFrmDb.Add("DocumentURL", "http://www.example.org/documents/1234"); 
     dataFrmDb.Add("ThumbnailURL", "http://www.example.org/thumbs/1234"); 
     dataFrmDb.Add("Abstract", "This is an example document."); 
     dataFrmDb.Add("Sector", "001"); 
     dataFrmDb.Add("Country", new List<string> { "USA", "Bulgaria", "France" }); 
     dataFrmDb.Add("Document Type", "example"); 

     dictList.Add(dataFrmDb); 
     return dictList; 
    } 
} 

輸出:

{ 
    "Documents": [ 
    { 
     "Title": "An Example Document", 
     "DatePublished": "4/9/2013 7:25:05 PM", 
     "DocumentURL": "http://www.example.org/documents/1234", 
     "ThumbnailURL": "http://www.example.org/thumbs/1234", 
     "Abstract": "This is an example document.", 
     "Sector": "001", 
     "Country": [ 
     "USA", 
     "Bulgaria", 
     "France" 
     ], 
     "Document Type": "example" 
    } 
    ] 
} 

稍微更簡單的方法來做到這一點是創建獨立的類來保存數據,如被建議Joey Gennari。 Json.NET也可以序列化這些。數據類會是這個樣子:

class Result 
{ 
    public List<Document> Documents { get; set; } 

    public Result() 
    { 
     Documents = new List<Document>(); 
    } 
} 

class Document 
{ 
    public string Title { get; set; } 
    public string DatePublished { get; set; } 
    public string DocumentURL { get; set; } 
    public string ThumbnailURL { get; set; } 
    public string Abstract { get; set; } 
    public string Sector { get; set; } 
    public List<string> Country { get; set; } 
    [JsonProperty(PropertyName="Document Type")] 
    public string DocumentType { get; set; } 

    public Document() 
    { 
     Country = new List<string(); 
    } 
} 

這裏是用法:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Document doc = new Document(); 
     doc.Title = "An Example Document"; 
     doc.DatePublished = DateTime.Now.ToString(); 
     doc.DocumentURL = "http://www.example.org/documents/1234"; 
     doc.ThumbnailURL = "http://www.example.org/thumbs/1234"; 
     doc.Abstract = "This is an example document."; 
     doc.Sector = "001"; 
     doc.Country.Add("USA"); 
     doc.Country.Add("Bulgaria"); 
     doc.Country.Add("France"); 
     doc.DocumentType = "example"; 

     Result result = new Result(); 
     result.Documents.Add(doc); 

     string json = JsonConvert.SerializeObject(result, Formatting.Indented); 
     System.Console.WriteLine(json); 
    } 
} 

這個例子的輸出是完全一樣的第一。

1

這是用DataContractJsonSerializer解決問題的另一種方法。首先創建一個類來表示對象:

[DataContract] 
    public class DocumentHolder 
    { 
     [DataMember(Name = "Documents")] 
     public Documents Document { get; set; } 
    } 

    [DataContract] 
    public class Documents 
    { 
     [DataMember(Name = "Title", Order = 1)] 
     public string Title { get; set; } 
     [DataMember(Name = "DatePublished", Order = 2)] 
     public DateTime? DatePublished { get; set; } 
     [DataMember(Name = "DocumentURL", Order = 3)] 
     public string DocumentURL { get; set; } 
     [DataMember(Name = "ThumbnailURL", Order = 4)] 
     public string ThumbnailURL { get; set; } 
     [DataMember(Name = "Abstract", Order = 5)] 
     public string Abstract { get; set; } 
     [DataMember(Name = "Sector", Order = 6)] 
     public string Sector { get; set; } 
     [DataMember(Name = "Country", Order = 7)] 
     public List<string> Country { get; set; } 
     [DataMember(Name = "Document Type", Order = 8)] 
     public string DocumentType { get; set; } 

     public Documents() 
     { 
      this.Country = new List<string>(); 
     } 
    } 

這裏是你將如何填補對象,並對其進行序列化:

static void Main(string[] args) 
    { 
     var documentholder = new DocumentHolder { Document = new Documents { Title = "Title 1", DatePublished = DateTime.Now, Sector = "A17", Country = new List<string> { "EN-US", "EN-GB" } } }; 
     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DocumentHolder)); 
     var ms = new MemoryStream(); 
     serializer.WriteObject(ms, documentholder); 
     var text = Encoding.UTF8.GetString(ms.ToArray()); 
    } 
+0

我使用的.NET 3.5我注意到,數據契約爲4.0和以上是否有另一種解決方案,你有什麼想法? – Kreston