0

我需要序列化一个如下所示的 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 对象添加带有“国家/地区”值的列表?还有其他方法可以解决这个问题吗?

4

2 回答 2

2

如果您更改dataFrmDb为 beDictionary<string, object>而不是 a Dictionary<string, string>,那么您可以像其他值一样将 Country 列表存储到其中。然后 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);
    }
}

此示例的输出与第一个完全相同。

于 2013-04-10T00:04:51.343 回答
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());
    }
于 2013-04-09T15:40:57.870 回答