如何在c#中将Json输出保存到SQLite数据库?

时间:2017-11-14 14:54:01

标签: c# json sqlite xamarin xamarin.forms

我正在尝试使用xamarin表单创建一个应用程序,从bittrex获取信息,然后将其放入模型中,然后将其保存到本地SQLite数据库。

以下是我将数据保存到数据库的代码:

    public class CoinsDatabase
{
    readonly SQLiteAsyncConnection database;

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

    public Task<List<Coins>> GetCoinsAsync()
    {
        return database.Table<Coins>().ToListAsync();
    }

    public Task<Coins> GetCoinsAsync(int id)
    {
        return database.Table<Coins>().Where(i => i.CoinID == id).FirstOrDefaultAsync();
    }

    public Task<int> SaveCoinAsync(Coins coin)
    {
        if(coin.CoinID == 0){
            return database.InsertAsync(coin);
        } else {
            return database.UpdateAsync(coin);
        }
    }

    public Task<int> DeleteCoinAsync(Coins coin)
    {
        return database.DeleteAsync(coin);
    }

以下是获取Json信息并进行处理的代码:

async void Save_Clicked(object sender, System.EventArgs e)
    {
        if (CoinNameEntry.Text != null){
            var uri = new Uri("https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-" + CoinNameEntry.Text.ToLower());

            HttpClient httpClient = new HttpClient();

            var response = await httpClient.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                Coins coins = JsonConvert.DeserializeObject<Coin>(content);
                var coinItem = (Coins)coins["result"].ToObject<Coins>();
                await App.Database.SaveCoinAsync(coinItem);
                await Navigation.PopAsync();
            } else {
                await DisplayAlert("Alert", "An error occured getting the coininformation of " + CoinNameEntry.Text.ToUpper(), "OK");
            }

        } else {
            await DisplayAlert("Alert", "Please select a Coin first", "OK");
        }
    }

这是我的钱币模型:

    public class Coins
{
    public List<Coin> coins { get; set; }
}
public class Coin
{
    [PrimaryKey, AutoIncrement]
    public int CoinID { get; set; }
    public string CoinName { get; set; }
    public bool Notification { get; set; }
    public string MarketName { get; set; }
    public double High { get; set; }
    public double Low { get; set; }
    public double Volume { get; set; }
    public double Last { get; set; }
    public double BaseVolume { get; set; }
    public bool TimeStamp { get; set; }
    public double Bid { get; set; }
    public double Ask { get; set; }
    public int OpenBuyOrders { get; set; }
    public int OpenSellOrders { get; set; }
    public double PrevDay { get; set; }
    public string Created { get; set; }

}

我一直试图让这个工作一个星期了,我想知道是否有人知道我做错了什么,或者是否有人有关于如何解决这个问题的提示。

请记住,我是xamarin和C#的初学者:)

1 个答案:

答案 0 :(得分:2)

好的,试试这个:首先,在您的硬币类中添加JsonProperty,将结果映射到正确的属性:

public class Coins
{
    [JsonProperty("result")]
    public List<Coin> coins { get; set; }
}

然后在代码中替换以下两行:

Coins coins = JsonConvert.DeserializeObject<Coin>(content);
var coinItem = (Coins)coins["result"].ToObject<Coins>();

Coins coins = JsonConvert.DeserializeObject<Coins>(content);
var coinItem = coins.coins[0];

请注意,这将为您提供列表中的第一个硬币 - 如果您想从列表中的其他位置检索硬币,请更改索引或使用LINQ。

我也非常怀疑你的SQLite代码不会做你想要的。目前,所有方法都作用于Coins对象而不是Coin对象。尝试将方法更改为

readonly SQLiteAsyncConnection database;

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

public Task<List<Coin>> GetCoinsAsync()
{
    return database.Table<Coin>().ToListAsync();
}

public Task<Coin> GetCoinsAsync(int id)
{
    return database.Table<Coin>().Where(i => i.CoinID == id).FirstOrDefaultAsync();
}

public Task<int> SaveCoinAsync(Coin coin)
{
    if(coin.CoinID == 0){
        return database.InsertAsync(coin);
    } else {
        return database.UpdateAsync(coin);
    }
}

public Task<int> DeleteCoinAsync(Coin coin)
{
    return database.DeleteAsync(coin);
}