Reputation: 65
I am writing a web app in ASP .Net Core, where I need to use JSON data from web API. I can get JSON from web using WebClient, so it looks like that in my code:
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(<credentials>);
var Json = wc.DownloadString("http://<JSON_String>");
JSON data I'm getting:
[
{
"ts_num": "6217",
"pl_date_first": "2021-10-01T06:53:07",
"pl_date_last": "2021-10-01T17:36:00",
"pl_num": "2-928558 ",
"pl_vod": "vod1",
"tank1_dn": 0,
"tank2_dn": 19.72,
"tank1_dn_count": 0,
"tank2_dn_count": 3
},
{
"ts_num": "3017",
"pl_date_first": "2021-10-01T06:54:10",
"pl_date_last": "2021-10-01T17:18:30",
"pl_num": "2-928362 ",
"pl_vod": "vod2",
"tank1_dn": 5.44,
"tank2_dn": 34.92,
"tank1_dn_count": 1,
"tank2_dn_count": 5
},
...
My problem is, I need to convert this JSON data into SQL table (I have an Azure SQL database), and preferably do it automatically since the data I need transferred to SQL is updating every month. But I couldn't find the way to do it specifically with data from web API. Is there a way to achieve that? Any helpful instructions or links will be much appreciated.
Upvotes: 0
Views: 1565
Reputation: 71159
You can upload the whole JSON to SQL Server and have it break it down into columns and rows
DECLARE @json nvarchar(max) = '
[
{
"ts_num": "6217",
"pl_date_first": "2021-10-01T06:53:07",
"pl_date_last": "2021-10-01T17:36:00",
"pl_num": "2-928558 ",
"pl_vod": "vod1",
"tank1_dn": 0,
"tank2_dn": 19.72,
"tank1_dn_count": 0,
"tank2_dn_count": 3
},
{
"ts_num": "3017",
"pl_date_first": "2021-10-01T06:54:10",
"pl_date_last": "2021-10-01T17:18:30",
"pl_num": "2-928362 ",
"pl_vod": "vod2",
"tank1_dn": 5.44,
"tank2_dn": 34.92,
"tank1_dn_count": 1,
"tank2_dn_count": 5
}]';
INSERT YourTable (
ts_num,
pl_date_first,
pl_date_last,
pl_num,
pl_vod,
tank1_dn,
tank2_dn,
tank1_dn_count,
tank2_dn_count
)
SELECT
ts_num,
CONVERT(datetime, pl_date_first, 126),
CONVERT(datetime, pl_date_last, 126),
pl_num,
pl_vod,
tank1_dn,
tank2_dn,
tank1_dn_count,
tank2_dn_count
FROM OPENJSON(@json)
WITH (
ts_num int,
pl_date_first varchar(19),
pl_date_last varchar(19),
pl_num varchar(30),
pl_vod varchar(30),
tank1_dn int,
tank2_dn decimal(18,9),
tank1_dn_count int,
tank2_dn_count int
) j;
Upvotes: 2