简体   繁体   中英

How to auto generate/create SQL server table from JSON in C#

I am getting JSON of Form Data from users. Below is the example of JSON Data

{  
   "Name":"Mike",
   "Age":25,
   "Gender":"Male",
   "Skills":{  
      ".Net":true,
      "Mule":""
   }
}

I want to save this data in a table (SQL Server). There is no table in the database, I want to define table name before sending this data to sql. Is there any approach to achieve this. Please help.

I suggest using json2csharp to convert the JSON to C# models and alter the names which are not recognized

    public class Skills
    {
        [JsonProperty(PropertyName = ".Net")] //Add JsonProperty to include unclassified names
        public bool DotNet { get; set; }
        public string Mule { get; set; }
    }

    public class RootObject10
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
        public Skills Skills { get; set; }
    }

then, you can deserialize the json using JsonConvert

using (StreamReader r = new StreamReader(filepath))
{
      string json = r.ReadToEnd();
      var obj = JsonConvert.DeserializeObject<RootObject10>(json);
}

After this, based on your requirement create single data table or 2 data tables and inject the data

Assuming your question is not about how to translate json into c# object but rather about how to store it in SQL Server while still being able to query it, you can actually work with json data in sql server: https://docs.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server?view=sql-server-ver15 .

I would opt for something like that if I didn't have schema upfront or I knew it will change often. Then I would create a table called FormData with an Id and Data fields and just stored your JSON in there.

Bear in mind this is likely less performant than defining tables and properly parsing json (which is covered by other answers here) - make sure you make the call after you've considered all pros and cons of schema-less storage.

Upd: if you absolutely must create tables at runtime you could potentially run plain SQL DDL statements like ´CREATE TABLE´ using plain ADO.NET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM