0

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.

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

OP is asking for a C# solution, not SQL directly.
We have no idea exactly what OP wanted anymore, given this Q is over 2 years old. But I think the point was: you can upload the whole JSON to SQL and shred it there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.