简体   繁体   中英

How to store JSON data into SQL Server database?

I have a JSON file. In that file around 1000 records. I am using C# and SQL Server.

My requirement is I want to store JSON file's records in to my table which created in SQL Server.

Can anyone tell me how to store JSON data in SQL Server using c# or JavaScript or jQuery anything?

It can be done by many ways. It depends on your need. if you do it very frequently then

  1. Simply upload the file on the server then process a schedule a job
    which processes all the record.

  2. Post your file on Server using Jquery then convert it to XML and pass it as a XML parameter to SQL Server procedure and then run insert command. This is not recommended for this type of bulk operation

This questions is a little old but here's an example. If you have SQL Server 2016 you can use a lot of built-in json functions SQL Server Json Support

Google newtonsoft json for examples (or whatever library you're using). I'm using the Newtonsoft.Json library. Make sure it's referenced in your project or add it via Nuget.

Your class should have a reference to it:

  using Newtonsoft.Json;

Converting C# list of ChartModel into json. The model (any POCO works) is defined as:

  public class ChartModel
  {
    public string ChartType { get; set; }
    public IList<ChartSeries> Data { get; set; }
    public string ChartTitle { get; set; }
    public int DisplayOrder { get; set; }
  }

Convert List to its json version:

  // Charts = List<ChartModel> 
  var chartJson = JsonConvert.SerializeObject(Charts);

  // or if you want the json formatted
  var chartJson = JsonConvert.SerializeObject(products, Formatting.Indented);

Now you have your json, a string, that can be stored in any nvarchar defined column.

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