追加到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對象中?還有另外一種方法可以解決這個問題嗎?
我使用的.NET 3.5我注意到,數據契約爲4.0和以上是否有另一種解決方案,你有什麼想法? – Kreston