[英]parse JSON file and insert data into SQL server
我有以下JSON对象并尝试创建INSERT查询。 创建数据并将数据插入数据库的最佳方法是什么? 我正在使用JSON.NET来解析文件。 我很感激任何建议。
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
if(reader.Value != null)
Console.WriteLine("Field: {0}, Value: {1}", reader.TokenType, reader.Value);
}
这是我的JSON看起来像。
{
"persons": {
"person": {
"i_date": "2014-03-20",
"i_location": "test",
"i_summary": "test test"
},
"people": {
"people1": {
"first_name": "first name test1",
"last_name": "last name test1"
},
"people2": {
"first_name": "first name test2",
"last_name": "last name test2"
},
"people3": {
"first_name": "first name test3",
"last_name": "last name test3"
}
}
}
}
首先,我重新构建了JSON,因此它更有意义。 你说一个“人”可以有多个“人”,所以这样构造它。 “人”有三个属性(即i_date,i_location和i_summary)和一组人。
{
"person":{
"i_date":"2014-03-20",
"i_location":"test",
"i_summary":"test test",
"people":[
{
"first_name":"first name test1",
"last_name":"last name test1"
},
{
"first_name":"first name test2",
"last_name":"last name test2"
},
{
"first_name": "first name test3",
"last_name":"last name test3"
}
]
}
}
现在,您可以声明一些表示结构的.NET类。
public class Person2
{
public string first_name { get; set; }
public string last_name { get; set; }
}
public class Person
{
public string i_date { get; set; }
public string i_location { get; set; }
public string i_summary { get; set; }
public List<Person2> people { get; set; }
}
public class RootObject
{
public Person person { get; set; }
}
最后,使用JsonConvert.DeserializeObject获取一组对象实例。
var root = JsonConvert.DeserializeObject<RootObject>( json );
你现在可以迭代附加在“人”身上的“人”并用它来做事。
Console.WriteLine( root.person.i_date );
Console.WriteLine( root.person.i_location );
Console.WriteLine( root.person.i_summary );
foreach(var p in root.person.people)
{
Console.WriteLine( p.first_name );
Console.WriteLine( p.last_name );
}
此时,您可以使用ADO.NET或Entity Framework将对象中的值传输到SQL参数(ADO.NET)或EF类中,以将其持久保存到数据库中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.