如何在C#中通过添加数据从JSON模式生成JSON文件

时间:2018-10-16 08:49:16

标签: c# json sql-server

我目前正在开发将SQL查询结果转换为JSON的应用程序。但是,转换后的JSON必须适合JSON Schema的一部分。我已经完成了第一部分,并且还将Schema加载到了应用程序中,但是我不知道如何根据加载的Schema生成JSON文件,并填充从SQL查询结果中获得的数据。

这是模式示例的一部分:

"security": [
 {
   "Default": []
 }
],
"components": {
"schemas": {
  "Event": {
    "title": "Event",
    "required": [
      "object",
      "body"
    ],
    "type": "object",
    "properties": {
      "object": {
        "type": "string",
        "description": "The object name involved in the event",
        "enum": [
          "business_partners"
        ]
      },
      "body": {
        "type": "object",
        "description": "The core data of the event",
        "required": [
          "name1",
          "country",
        ],
        "properties": {
          "name1": {
            "type": "string",
            "description": "Partner Name 1"
          },
          "name2": {
            "type": "string",
            "description": "Partner Name 2"
          },
          "country": {
            "type": "string",
            "description": "Country ISO Code"
          },
        }
      }
    }
  },

从查询结果中,我可以拥有属性name1name2country

转换为JSON后,查询结果JSON如下所示:

 [
  {
    "Partner Name 1": "Jenny",
    "Partner Name 2": null,
    "Country ISO Code": "US",
  },
  {
    "Partner Name 1": "John",
    "Partner Name 2": "Alan",
    "Country ISO Code": null,
  },
]

我如何生成具有模式中所有其他字段的JSON文件,但仅将SQL查询结果中的值填充到JSON文件中?

我在此项目中使用Newtonsoft.JsonNewtonsoft.Json.Schema

注意:除了SQL查询结果返回的数据外,生成的JSON文件还需要查询结果中不存在的那些字段。

到目前为止,这是我的代码:

    private IEnumerable<dynamic> ReaderToAnonymmous()
    {
        //Connect to SQL Database using App.config
        string connectionString = ConfigurationManager.AppSettings["SQLConnection"].ToString();
        SqlConnection connection = new SqlConnection(connectionString);

        //Using Stored Procedure to execute query (Full Script Written inside SQLScript folder)
        SqlCommand command = new SqlCommand("Select_Result_Convert_JSON", connection)
        {
            CommandType = CommandType.StoredProcedure
        };

        connection.Open();

        using (var reader = command.ExecuteReader())
        {
            var schemaTable = reader.GetSchemaTable();

            List<string> colnames = new List<string>();
            foreach (DataRow row in schemaTable.Rows)
            {
                colnames.Add(row["ColumnName"].ToString());
            }

            while (reader.Read())
            {
                var data = new ExpandoObject() as IDictionary<string, Object>;
                foreach (string colname in colnames)
                {
                    var val = reader[colname];
                    data.Add(colname, Convert.IsDBNull(val) ? null : val);
                }

                yield return (ExpandoObject)data;
            }
        }
    }

private void LoadSchema()
{
    using (StreamReader file = File.OpenText("..\\..\\sampleschema.json"))
    using (JsonTextReader reader = new JsonTextReader(file))
    {
        schema = JSchema.Load(reader);
    }
}

public void generateJSONFile(string fileName)
{
    try
    {
        var ObjectData = ReaderToAnonymmous(); //Get the SQL Query Result and Convert it to object
        LoadSchema();

        var Json = JsonConvert.SerializeObject(ObjectData);
        JArray BP = new JArray(Json);

        if (BP.IsValid(schema))
        {
            BP.Merge(schema);
            if (!String.IsNullOrEmpty(fileName)) //If user enter any file name
            {
                string basePath = String.Format("{0}{1}{2}", "C:\\", fileName, ".json");

                using (StreamWriter file = File.CreateText(basePath)) //Create JSON File based on input name
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Formatting = Formatting.Indented; //Format the JSON
                    serializer.Serialize(file, BP);
                }
           }
        }
   catch (Exception ex)
   {
        MessageBox.Show(ex.Message, "Error Message", MessageBoxButton.OK, MessageBoxImage.Error);
   } 
}

请帮助!谢谢!

0 个答案:

没有答案