我使用C#对URL进行API调用,然后返回JSon响应并下载json文件。
我想将json数据写入数据库以供Web应用程序使用。 如何将json文件导入sql或直接从我的c#程序写入db。我正在使用sql 2016
我的JSon文件如下所示:
{
"Items": [
{
"LocalTimestamp": "2017-07-05T18:59:29+02:00",
"Id": 653914348,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.90225,
-26.07706
]
},
{
"LocalTimestamp": "2017-07-05T08:41:08+02:00",
"Id": 653709051,
"Description": "Trip Startup",
"Processed": false,
"Position": [
27.90229,
-26.07753
]
},
{
"LocalTimestamp": "2017-07-05T07:42:19+02:00",
"Id": 653692142,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.90228,
-26.07708
]
},
{
"LocalTimestamp": "2017-07-05T07:21:47+02:00",
"Id": 653683088,
"Description": "Trip Startup",
"Processed": false,
"Position": [
27.9222,
-26.04318
]
},
{
"LocalTimestamp": "2017-07-05T07:21:00+02:00",
"Id": 653682830,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.92348,
-26.04612
]
},
{
"LocalTimestamp": "2017-07-04T10:15:35+02:00",
"Id": 653330923,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.997,
-26.05747
]
},
{
"LocalTimestamp": "2017-07-04T09:41:19+02:00",
"Id": 653320268,
"Description": "Trip Startup",
"Processed": false,
"Position": [
28.02899,
-26.20546
]
},
{
"LocalTimestamp": "2017-07-04T09:32:54+02:00",
"Id": 653317769,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
28.0293,
-26.20549
]
},
{
"LocalTimestamp": "2017-07-03T18:40:43+02:00",
"Id": 653089737,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.90228,
-26.07707
]
},
{
"LocalTimestamp": "2017-07-03T18:29:01+02:00",
"Id": 653086470,
"Description": "Trip Startup",
"Processed": false,
"Position": [
27.94599,
-26.07828
]
},
{
"LocalTimestamp": "2017-07-03T18:26:30+02:00",
"Id": 653085810,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.94662,
-26.07807
]
},
{
"LocalTimestamp": "2017-07-03T18:15:50+02:00",
"Id": 653082613,
"Description": "Trip Startup",
"Processed": false,
"Position": [
27.98847,
-26.05269
]
},
{
"LocalTimestamp": "2017-07-03T18:13:15+02:00",
"Id": 653082018,
"Description": "Trip Shutdown",
"Processed": false,
"Position": [
27.99036,
-26.05341
]
}
],
"HasMoreResults": false
}
答案 0 :(得分:2)
确定。正如我在评论中提到的,你必须将你收到的json字符串反序列化为object / class,并使用c#将该类/对象属性保存到数据库。
在数据库中,您需要根据“json字符串结构”或“类/对象”创建表。
根据您的json字符串,该类应如下所示
public class Item
{
public string LocalTimestamp { get; set; }
public int Id { get; set; }
public string Description { get; set; }
public bool Processed { get; set; }
public List<double> Position { get; set; }
}
public class AllItems
{
public List<Item> Items { get; set; }
public bool HasMoreResults { get; set; }
}
要反序列化json字符串,下面是代码,为此,您需要名称空间“System.Web.Script.Serialization
”。
string jsonstring = @"define your json string here";
//Deserialize the json string to the object/class format
var serializer = new JavaScriptSerializer();
AllItems allItemsObj = serializer.Deserialize<AllItems>(jsonstring);
根据json字符串结构
创建数据库表CREATE TABLE AllItemsTable (
ItemIdPrimary int NOT NULL IDENTITY(1,1),
LocalTimestamp nvarchar(255),
Id int,
Description nvarchar(255),
Processed nvarchar(255),
Position1 nvarchar(50),
Position2 nvarchar(50)
PRIMARY KEY (ItemIdPrimary)
);
这里是完整的代码,用于反序列化json字符串并保存数据 到数据库。
对于jsonstring,我在里面添加了一个名为“test1.json”的json文件 应用程序并将您的json字符串复制到json文件。我是 从该文件中消耗json(“test1.json”)
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Configuration;
namespace DeserializeJson2ConsoleApp
{
class Program
{
static void Main(string[] args)
{
//Get the Json string
string jsonstring = File.ReadAllText(@"D:\My Apps\Console Applications\DeserializeJson2ConsoleApp\DeserializeJson2ConsoleApp\test1.json");
//Deserialize the json string to the object/class format
var serializer = new JavaScriptSerializer();
AllItems allItemsObj = serializer.Deserialize<AllItems>(jsonstring);
//Save the deserilized object/class to database
//Get your connection string defined inside the Web.config(for web application) / App.config(for console/windows/wpf/classlibrary application) file
string myConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
//Create your Sql Connection here
using (SqlConnection con = new SqlConnection(myConnectionString))
{
//Open the sql connection
con.Open();
//Loop each items and save to database
foreach (var item in allItemsObj.Items)
{
//Save/Insert to database
if(SaveToDatabase(con, item))
{
Console.WriteLine("Success : " + item.Description + " Saved into database");
}
else
{
Console.WriteLine("Error : " + item.Description + " unable to Saved into database");
}
}
}
Console.Read();
}
/// <summary>
/// Insert to database
/// </summary>
/// <param name="con"></param>
/// <param name="aItemObj"></param>
/// <returns></returns>
static bool SaveToDatabase(SqlConnection con,Item aItemObj)
{
try
{
string insertQuery = @"Insert into AllItemsTable(LocalTimestamp,Id,Description,Processed,Position1,Position2) Values(@LocalTimestamp,@Id,@Description,@Processed,@Position1,@Position2)";
using (SqlCommand cmd = new SqlCommand(insertQuery, con))
{
cmd.Parameters.Add(new SqlParameter("@LocalTimestamp",aItemObj.LocalTimestamp));
cmd.Parameters.Add(new SqlParameter("@Id", aItemObj.Id));
cmd.Parameters.Add(new SqlParameter("@Description", aItemObj.Description));
cmd.Parameters.Add(new SqlParameter("@Processed", aItemObj.Processed));
for(int index=0;index<aItemObj.Position.Count;index++)
{
if(index==0)
cmd.Parameters.Add(new SqlParameter("@Position1", aItemObj.Position[index].ToString()));
else
cmd.Parameters.Add(new SqlParameter("@Position2", aItemObj.Position[index].ToString()));
}
cmd.ExecuteNonQuery();
}
return true;
}
catch (Exception objEx)
{
return false;
}
}
}
public class Item
{
public string LocalTimestamp { get; set; }
public int Id { get; set; }
public string Description { get; set; }
public bool Processed { get; set; }
public List<double> Position { get; set; }
}
public class AllItems
{
public List<Item> Items { get; set; }
public bool HasMoreResults { get; set; }
}
}
这是数据保存到数据库后控制台中的消息。
以下是已保存到数据库的数据。
希望,它解决了你的问题。如果您有任何问题,请将我还原。