gpt4 book ai didi

c# - 将 JSON 反序列化为 SQLite 数据库

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:53 28 4
gpt4 key购买 nike

我的模型是 GasStation

using Newtonsoft.Json;
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;

namespace TDEv2.Models
{
public class GasStation
{
[JsonProperty("costcentre")][PrimaryKey]
public string CostCentre { get; set; }

[JsonProperty("name")]
public string Name { get; set; }

[JsonProperty("id")]
public string Id { get; set; }
}
}

我的 GasStationQuery 包含这个:

namespace TDEv2.Models
{
public class GasStationQuery
{
public GasStation[] GasStations { get; set; }
}
}

我的 JSON 数组如下所示:

    gasstations: [
{
"id": 01,
"name": "GasStation1",
"costcentre": 123
},
{
"id": 02,
"name": "GasStation2",
"costcentre": 456
}
]

现在我想将其反序列化到我的 SQLite 数据库中:

using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TDEv2.Models;

namespace TDEv2.Data
{
public class GasStationDatabase
{

readonly SQLiteAsyncConnection database;

public GasStationDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<GasStation>().Wait();
}

public Task<List<GasStation>> GetItemsAsync()
{
return database.Table<GasStation>().ToListAsync();
}

public Task<GasStation> GetItemAsync(string costCentre)
{
return database.Table<GasStation>().Where(i => i.CostCentre == costCentre).FirstOrDefaultAsync();
}

public Task<int> SaveItemAsync(GasStation gasStation)
{
if (gasStation.CostCentre != null)
{
return database.UpdateAsync(gasStation);
}
else
{
return database.InsertAsync(gasStation);
}
}

}
}

现在我想进行初始同步以填充我的数据库以便在设备上离线工作,但我不知道进一步的步骤,因为我的编程时间不长。

这是我填充数据库的尝试:

using System.Net;
using TDEv2.Data;
using TDEv2.Models;

namespace TDEv2.Services
{
public class InitialAsyncGasStationDatabase
{
private GasStationDatabase db;
public GasStationQuery InitialAsyncGasStationsToDatabase()
{
string json;
using (WebClient client = new WebClient())
{
json = client.DownloadString($"http://xxx/gasstations.json");
}
foreach (GasStation gasStation in json)
{
db.SaveItemAsync(gasStation);
}
return;
}
}
}

代码无效。我在 foreach 部分遇到错误,其中包含 Cannot convert type "char"to "TDEv2.Models.GasStation"

最佳答案

你需要将你的json反序列化到一个对象中,然后才能将它保存到数据库中

        using (WebClient client = new WebClient())
{
json = client.DownloadString($"http://xxx/gasstations.json");
}

// using newtonsoft json.net - use http://json2csharp.com/ to verfiy
// that your C# model class actually matches your json
var data = JsonConvert.DeserializeObject<GasStationQuery>(json);

foreach (GasStation gasStation in data.GasStations)
{
db.SaveItemAsync(gasStation);
}

关于c# - 将 JSON 反序列化为 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52257874/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com