使用JSON.net附加到JSON对象 [英] Appending to JSON object using JSON.net

查看:63
本文介绍了使用JSON.net附加到JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要序列化如下所示的JSON对象:

I need to serialize a JSON object that looks like this:

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

我正在做的是从SQL Server中获取数据并将结果存储到这样的对象中:

What I'm doing is taking the data from SQL server and storing the results into an object like this:

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;
}

然后我获取这些数据并像这样进行序列化:

I then take this data and serialize like this:

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格式查看,则"Country"需要具有多个值.我不知道如何将其实现到此JSON对象中.如何使用JSON.net将带有国家/地区"值的列表添加到JSON对象?还有另一种方法可以解决这个问题吗?

I get the proper output but if you would look in the original JSON format, "Country" needs to have multiple values. I don't know how to implement that into this JSON object. How do I add a list with the "Country" values to the JSON object using JSON.net? Is there another way to go about this?

推荐答案

如果将dataFrmDb更改为Dictionary<string, object>而不是Dictionary<string, string>,则可以像其他值一样将国家/地区"列表存储到其中.然后,Json.Net将根据需要对其进行序列化.

If you change dataFrmDb to be Dictionary<string, object> instead of a Dictionary<string, string>, then you can store the Countries list into it like the other values. Json.Net will then serialize it like you want.

这是一个示例程序,演示:

Here is an example program which demonstrates:

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也可以序列化它们.数据类如下所示:

A somewhat more straightforward way to do it is to create separate classes to hold the data, as was suggested by Joey Gennari. Json.NET can serialize those as well. The data classes would look something like this:

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);
    }
}

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

The output for this example is exactly the same as the first.

这篇关于使用JSON.net附加到JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆