簡體   English   中英

解析JSON文件並將數據插入SQL服務器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM