我需要序列化一个如下所示的 JSON 对象:
{
"Documents": [
{
"Title": "",
"DatePublished": "",
"DocumentURL": "",
"ThumbnailURL": "",
"Abstract": "",
"Sector": "",
"Country": [
"", "", ""
],
"Document Type": ""
}
]
}
我正在做的是从 SQL 服务器获取数据并将结果存储到这样的对象中:
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);
我得到了正确的输出,但是如果您查看原始 JSON 格式,“国家/地区”需要有多个值。我不知道如何在这个 JSON 对象中实现它。如何使用 JSON.net 向 JSON 对象添加带有“国家/地区”值的列表?还有其他方法可以解决这个问题吗?