简体   繁体   中英

How do I save Json output to a SQLite database in c#?

I'm trying to make an app in xamarin forms that gets information from bittrex then puts it into a model and then saves it to the local SQLite database.

Here is my code for saving things to the database:

    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);
    }

Here is my code for getting the Json information and processing it:

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");
        }
    }

And this is my Coins model:

    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; }

}

I have been trying to get this working for a week now and I was wondering if someone knows what i do wrong or if someone has tips on how to fix this problem.

Please keep in mind that im a beginner with xamarin and C# :)

OK, try this: First, add a JsonProperty to your coins class to map the result to the correct property:

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

Then replace the following two lines in your code:

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

with

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

Please note that this will give you the first of the coins in the list - change the index or use LINQ if you want to retrieve a coin from somewhere else in the list.

I also very much suspect that your SQLite code won't do what you want. Currently all your methods act on a Coins object rather than a Coin object. Try changing the methods to

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM